public static function Toolbox() { //if not the first time this is called if (isset(self::$toolbox)) { return self::$toolbox; } //else set up the RedBean toolbox require_once \Swiftriver\Core\Setup::Configuration()->ModulesDirectory . "/RedBean/redbean.inc.php"; //get the url of the url of the db server $url = (string) Setup::$Configuration->DataBaseUrl; //Get the db username $username = (string) Setup::$Configuration->UserName; //get the password $password = (string) Setup::$Configuration->Password; //get the db name $database = (string) Setup::$Configuration->Database; //set the db type $typeofdatabase = "mysql"; //Assemble a database connection string (DSN) $dsn = "{$typeofdatabase}:host={$url};dbname={$database}"; //Construct a new Red Bean Toolbox, if it has not been set in the mean time if (!isset(self::$toolbox)) { self::$toolbox = \RedBean_Setup::kickstartDev($dsn, $username, $password); } //return it return self::$toolbox; }
/** * Fetches a collection of OODB Bean objects based on the SQL * criteria provided. For instance; * * - Finder::where("page", " name LIKE '%more%' "); * * Will return all pages that have the word 'more' in their name. * The second argument is actually just plain SQL; the function expects * this SQL to be compatible with a SELECT * FROM TABLE WHERE X query, * where X is ths search string you provide in the second parameter. * Another example, using slots: * * - Finder::where("page", " name LIKE :str ",array(":str"=>'%more%')); * * Also, note that the default search is always 1. So if you do not * specify a search parameter this function will just return every * bean of the given type: * * - Finder::where("page"); //returns all pages * * * @param string $type * @param string $SQL * @param array $values * @return array $beans */ public static function where($type, $SQL = " 1 ", $values = array()) { //Sorry, quite draconic filtering $type = preg_replace("/\\W/", "", $type); //First get hold of the toolbox $tools = RedBean_Setup::getToolBox(); RedBean_CompatManager::scanDirect($tools, array(RedBean_CompatManager::C_SYSTEM_MYSQL => "5")); //Now get the two tools we need; RedBean and the Adapter $redbean = $tools->getRedBean(); $adapter = $tools->getDatabaseAdapter(); //Make a standard ANSI SQL query from the SQL provided try { $SQL = "SELECT * FROM {$type} WHERE " . $SQL; //Fetch the values using the SQL and value pairs provided $rows = $adapter->get($SQL, $values); } catch (RedBean_Exception_SQL $e) { if ($e->getSQLState() == "42S02" || $e->getSQLState() == "42S22") { //no such table? no problem. may happen. return array(); } else { throw $e; } } //Give the rows to RedBean OODB to convert them //into beans. return $redbean->convertToBeans($type, $rows); }
/** * * Constructor, requires a type name * @param string $typeName */ public function __construct($typeName) { $this->tools = RedBean_Setup::getToolBox(); $this->redbean = $this->tools->getRedBean(); $this->bean = $this->redbean->dispense($typeName); $this->associationManager = new RedBean_AssociationManager($this->tools); $this->treeManager = new RedBean_TreeManager($this->tools); }
/** * Ensures that given an association between * $bean1 and $bean2, * if one of them gets trashed the association will be * automatically removed. * @param RedBean_OODBBean $bean1 * @param RedBean_OODBBean $bean2 * @return boolean $addedFKS */ public static function addConstraint(RedBean_OODBBean $bean1, RedBean_OODBBean $bean2, $dontCache = false) { //Fetch the toolbox $toolbox = RedBean_Setup::getToolBox(); RedBean_CompatManager::scanDirect($toolbox, array(RedBean_CompatManager::C_SYSTEM_MYSQL => "5")); //Create an association manager $association = new RedBean_AssociationManager($toolbox); $writer = $toolbox->getWriter(); $oodb = $toolbox->getRedBean(); $adapter = $toolbox->getDatabaseAdapter(); //Frozen? Then we may not alter the schema! if ($oodb->isFrozen()) { return false; } //$adapter->getDatabase()->setDebugMode(1); $table1 = $bean1->getMeta("type"); $table2 = $bean2->getMeta("type"); $table = $association->getTable(array($table1, $table2)); $idfield1 = $writer->getIDField($bean1->getMeta("type")); $idfield2 = $writer->getIDField($bean2->getMeta("type")); $bean = $oodb->dispense($table); $property1 = $bean1->getMeta("type") . "_id"; $property2 = $bean2->getMeta("type") . "_id"; if ($property1 == $property2) { $property2 = $bean2->getMeta("type") . "2_id"; } $table = $adapter->escape($table); $table1 = $adapter->escape($table1); $table2 = $adapter->escape($table2); $property1 = $adapter->escape($property1); $property2 = $adapter->escape($property2); //In Cache? Then we dont need to bother if (isset(self::$fkcache[$table])) { return false; } $db = $adapter->getCell("select database()"); $fks = $adapter->getCell("\n\t\t\tSELECT count(*)\n\t\t\tFROM information_schema.KEY_COLUMN_USAGE\n\t\t\tWHERE TABLE_SCHEMA ='{$db}' AND TABLE_NAME ='{$table}' AND\n\t\t\tCONSTRAINT_NAME <>'PRIMARY' AND REFERENCED_TABLE_NAME is not null\n\t\t"); //already foreign keys added in this association table if ($fks > 0) { return false; } //add the table to the cache, so we dont have to fire the fk query all the time. if (!$dontCache) { self::$fkcache[$table] = true; } $columns = $writer->getColumns($table); if ($writer->code($columns[$property1]) !== RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32) { $writer->widenColumn($table, $property1, RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32); } if ($writer->code($columns[$property2]) !== RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32) { $writer->widenColumn($table, $property2, RedBean_QueryWriter_MySQL::C_DATATYPE_UINT32); } $sql = "\n\t\t\tALTER TABLE " . $writer->noKW($table) . "\n\t\t\tADD FOREIGN KEY({$property1}) references {$table1}(id) ON DELETE CASCADE;\n\n\t\t"; $adapter->exec($sql); $sql = "\n\t\t\tALTER TABLE " . $writer->noKW($table) . "\n\t\t\tADD FOREIGN KEY({$property2}) references {$table2}(id) ON DELETE CASCADE\n\t\t"; $adapter->exec($sql); return true; }
/** * @param string $dsn * @param string $username * @param string $password * @return RedBean_ToolBox $toolbox */ public static function kickstart($dsn, $username, $password) { $pdo = new Redbean_Driver_PDO($dsn, $username, $password); $adapter = new RedBean_DBAdapter($pdo); $writer = new RedBean_QueryWriter_MySQL($adapter); $redbean = new RedBean_OODB($writer); //add concurrency shield $logger = new RedBean_ChangeLogger($writer); self::$observers["logger"] = $logger; $redbean->addEventListener("open", $logger); $redbean->addEventListener("update", $logger); $redbean->addEventListener("delete", $logger); //deliver everything back in a neat toolbox self::$toolbox = new RedBean_ToolBox($redbean, $adapter, $writer); return self::$toolbox; }
/** * Test closing database connection. * * @return void */ public function testClose() { asrt(R::$adapter->getDatabase()->isConnected(), TRUE); R::close(); asrt(R::$adapter->getDatabase()->isConnected(), FALSE); // Can we create a database using empty setup? R::setup(); $id = R::store(R::dispense('bean')); asrt($id > 0, TRUE); // Test freeze via kickstart in setup $toolbox = RedBean_Setup::kickstart('sqlite:/tmp/bla.txt', NULL, NULL, TRUE); asrt($toolbox->getRedBean()->isFrozen(), TRUE); // Test Oracle setup $toolbox = RedBean_Setup::kickstart('oracle:test-value', 'test', 'test', FALSE); asrt($toolbox instanceof RedBean_ToolBox, TRUE); }
/** * Fetches a collection of OODB Bean objects based on the SQL * criteria provided. For instance; * * - Finder::where("page", " name LIKE '%more%' "); * * Will return all pages that have the word 'more' in their name. * The second argument is actually just plain SQL; the function expects * this SQL to be compatible with a SELECT * FROM TABLE WHERE X query, * where X is ths search string you provide in the second parameter. * Another example, using slots: * * - Finder::where("page", " name LIKE :str ",array(":str"=>'%more%')); * * Also, note that the default search is always 1. So if you do not * specify a search parameter this function will just return every * bean of the given type: * * - Finder::where("page"); //returns all pages * * * @param string $type * @param string $SQL * @param array $values * @return array $beans */ public static function where($type, $SQL = " 1 ", $values = array()) { //Sorry, quite draconic filtering $type = preg_replace("/\\W/", "", $type); //First get hold of the toolbox $tools = RedBean_Setup::getToolBox(); //Now get the two tools we need; RedBean and the Adapter $redbean = $tools->getRedBean(); $adapter = $tools->getDatabaseAdapter(); //Make a standard ANSI SQL query from the SQL provided $SQL = "SELECT * FROM {$type} WHERE " . $SQL; //Fetch the values using the SQL and value pairs provided $rows = $adapter->get($SQL, $values); //Give the rows to RedBean OODB to convert them //into beans. return $redbean->convertToBeans($type, $rows); }
/** * Kickstarts redbean for you. * @param string $dsn * @param string $username * @param string $password */ public static function setup($dsn = "sqlite:/tmp/red.db", $username = NULL, $password = NULL) { RedBean_Setup::kickstart($dsn, $username, $password); self::$toolbox = RedBean_Setup::getToolBox(); self::$writer = self::$toolbox->getWriter(); self::$adapter = self::$toolbox->getDatabaseAdapter(); self::$redbean = self::$toolbox->getRedBean(); self::$associationManager = new RedBean_AssociationManager(self::$toolbox); self::$treeManager = new RedBean_TreeManager(self::$toolbox); self::$linkManager = new RedBean_LinkManager(self::$toolbox); self::$extAssocManager = new RedBean_ExtAssociationManager(self::$toolbox); $helper = new RedBean_ModelHelper(); self::$redbean->addEventListener("update", $helper); self::$redbean->addEventListener("open", $helper); self::$redbean->addEventListener("delete", $helper); }
/** * Adds a database to the facade, afterwards you can select the database using * selectDatabase($key), where $key is the name you assigned to this database. * * Usage: * * R::addDatabase( 'database-1', 'sqlite:/tmp/db1.txt' ); * R::selectDatabase( 'database-1' ); //to select database again * * This method allows you to dynamically add (and select) new databases * to the facade. Adding a database with the same key will cause an exception. * * @param string $key ID for the database * @param string $dsn DSN for the database * @param string $user User for connection * @param NULL|string $pass Password for connection * @param bool $frozen Whether this database is frozen or not * * @return void */ public static function addDatabase($key, $dsn, $user = NULL, $pass = NULL, $frozen = FALSE, $autoSetEncoding = TRUE) { if (isset(self::$toolboxes[$key])) { throw new RedBean_Exception_Security('A database has already be specified for this key.'); } self::$toolboxes[$key] = RedBean_Setup::kickstart($dsn, $user, $pass, $frozen, $autoSetEncoding); }
/** * Kickstarts redbean for you. * @param string $dsn * @param string $username * @param string $password */ public static function setup( $dsn="sqlite:/tmp/red.db", $username=NULL, $password=NULL ) { RedBean_Setup::kickstart( $dsn, $username, $password ); $toolbox = RedBean_Setup::getToolBox(); self::configureFacadeWithToolbox($toolbox); }
/** * Test Facade transactions. * * @return void * * @throws Exception */ public function testTransactionInFacade() { testpack('Test transaction in facade'); $bean = R::dispense('bean'); $bean->name = 'a'; R::store($bean); R::trash($bean); R::freeze(TRUE); $bean = R::dispense('bean'); $bean->name = 'a'; R::store($bean); asrt(R::count('bean'), 1); R::trash($bean); asrt(R::count('bean'), 0); $bean = R::dispense('bean'); $bean->name = 'a'; $id = R::transaction(function () use(&$bean) { return R::transaction(function () use(&$bean) { return R::store($bean); }); }); asrt((int) $id, (int) $bean->id); R::trash($bean); $bean = R::dispense('bean'); $bean->name = 'a'; $id = R::transaction(function () use(&$bean) { return R::store($bean); }); asrt((int) $id, (int) $bean->id); R::trash($bean); $bean = R::dispense('bean'); $bean->name = 'a'; try { R::transaction(function () use($bean) { R::store($bean); R::transaction(function () { throw new Exception(); }); }); } catch (Exception $e) { pass(); } asrt(R::count('bean'), 0); $bean = R::dispense('bean'); $bean->name = 'a'; try { R::transaction(function () use($bean) { R::transaction(function () use($bean) { R::store($bean); throw new Exception(); }); }); } catch (Exception $e) { pass(); } asrt(R::count('bean'), 0); $bean = R::dispense('bean'); $bean->name = 'a'; try { R::transaction(function () use($bean) { R::transaction(function () use($bean) { R::store($bean); }); }); } catch (Exception $e) { pass(); } asrt(R::count('bean'), 1); R::freeze(FALSE); try { R::transaction('nope'); fail(); } catch (Exception $e) { pass(); } testpack('Test Camelcase 2 underscore'); $names = array('oneACLRoute' => 'one_acl_route', 'ALLUPPERCASE' => 'alluppercase', 'clientServerArchitecture' => 'client_server_architecture', 'camelCase' => 'camel_case', 'peer2peer' => 'peer2peer', 'fromUs4You' => 'from_us4_you', 'lowercase' => 'lowercase', 'a1A2b' => 'a1a2b'); $bean = R::dispense('bean'); foreach ($names as $name => $becomes) { $bean->{$name} = 1; asrt(isset($bean->{$becomes}), TRUE); } testpack('Test debugger check.'); $old = R::$adapter; R::$adapter = NULL; try { R::debug(TRUE); fail(); } catch (RedBean_Exception_Security $e) { pass(); } R::$adapter = $old; R::debug(FALSE); testpack('Misc Tests'); try { $candy = R::dispense('CandyBar'); fail(); } catch (RedBean_Exception_Security $e) { pass(); } $candy = R::dispense('candybar'); $s = strval($candy); asrt($s, 'candy!'); $obj = new stdClass(); $bean = R::dispense('bean'); $bean->property1 = 'property1'; $bean->exportToObj($obj); asrt($obj->property1, 'property1'); R::debug(1); flush(); ob_start(); R::exec('SELECT 123'); $out = ob_get_contents(); ob_end_clean(); flush(); pass(); asrt(strpos($out, 'SELECT 123') !== FALSE, TRUE); R::debug(0); flush(); ob_start(); R::exec('SELECT 123'); $out = ob_get_contents(); ob_end_clean(); flush(); pass(); asrt($out, ''); R::debug(0); pass(); testpack('test to string override'); $band = R::dispense('band'); $str = strval($band); asrt($str, 'bigband'); testpack('test whether we can use isset/set in model'); $band->setProperty('property1', 123); asrt($band->property1, 123); asrt($band->checkProperty('property1'), TRUE); asrt($band->checkProperty('property2'), FALSE); $band = new Model_Band(); $bean = R::dispense('band'); $bean->property3 = 123; $band->loadBean($bean); $bean->property4 = 345; $band->setProperty('property1', 123); asrt($band->property1, 123); asrt($band->checkProperty('property1'), TRUE); asrt($band->checkProperty('property2'), FALSE); asrt($band->property3, 123); asrt($band->property4, 345); testpack('Test blackhole DSN and setup()'); R::setup('blackhole:database'); pass(); asrt(isset(R::$toolboxes['default']), TRUE); try { R::$toolboxes['default']->getDatabaseAdapter()->getDatabase()->connect(); fail(); } catch (PDOException $e) { pass(); /** * Make sure the message is non-descriptive - avoid revealing * security details if user hasn't configured error reporting improperly. */ asrt($e->getMessage(), 'Could not connect to database (?).'); } R::setup('blackhole:dbname=mydatabase;password=dontshowthisone'); pass(); asrt(isset(R::$toolboxes['default']), TRUE); try { R::$toolboxes['default']->getDatabaseAdapter()->getDatabase()->connect(); fail(); } catch (PDOException $e) { pass(); /** * Make sure the message is non-descriptive - avoid revealing * security details if user hasn't configured error reporting improperly. */ asrt($e->getMessage(), 'Could not connect to database (mydatabase).'); } testpack('Can we pass a PDO object to Setup?'); $pdo = new PDO('sqlite:test.db'); $toolbox = RedBean_Setup::kickstart($pdo); asrt($toolbox instanceof RedBean_ToolBox, TRUE); asrt($toolbox->getDatabaseAdapter() instanceof RedBean_Adapter, TRUE); asrt($toolbox->getDatabaseAdapter()->getDatabase()->getPDO() instanceof PDO, TRUE); testpack('Test array interface of beans'); $bean = R::dispense('bean'); $bean->hello = 'hi'; $bean->world = 'planet'; asrt($bean['hello'], 'hi'); asrt(isset($bean['hello']), TRUE); asrt(isset($bean['bye']), FALSE); $bean['world'] = 'sphere'; asrt($bean->world, 'sphere'); foreach ($bean as $key => $el) { if ($el == 'sphere' || $el == 'hi' || $el == 0) { pass(); } else { fail(); } if ($key == 'hello' || $key == 'world' || $key == 'id') { pass(); } else { fail(); } } asrt(count($bean), 3); unset($bean['hello']); asrt(count($bean), 2); asrt(count(R::dispense('countable')), 1); // Otherwise untestable... $bean->setBeanHelper(new RedBean_BeanHelper_Facade()); R::$redbean->setBeanHelper(new RedBean_BeanHelper_Facade()); pass(); // Test whether properties like owner and shareditem are still possible testpack('Test Bean Interface for Lists'); $bean = R::dispense('bean'); // Must not be list, because first char after own is lowercase asrt(is_array($bean->owner), FALSE); // Must not be list, because first char after shared is lowercase asrt(is_array($bean->shareditem), FALSE); asrt(is_array($bean->own), FALSE); asrt(is_array($bean->shared), FALSE); asrt(is_array($bean->own_item), FALSE); asrt(is_array($bean->shared_item), FALSE); asrt(is_array($bean->{'own item'}), FALSE); asrt(is_array($bean->{'shared Item'}), FALSE); }
/** * Adds a database to the facade, afterwards you can select the database using * selectDatabase($key). * * @param string $key ID for the database * @param string $dsn DSN for the database * @param string $user User for connection * @param null|string $pass Password for connection * @param bool $frozen Whether this database is frozen or not * * @return void */ public static function addDatabase($key, $dsn, $user = null, $pass = null, $frozen = false) { self::$toolboxes[$key] = RedBean_Setup::kickstart($dsn, $user, $pass, $frozen); }
/** * Adds a database to the facade, afterwards you can select the database using * selectDatabase($key), where $key is the name you assigned to this database. * * Usage: * * R::addDatabase( 'database-1', 'sqlite:/tmp/db1.txt' ); * R::selectDatabase( 'database-1' ); //to select database again * * This method allows you to dynamically add (and select) new databases * to the facade. Adding a database with the same key as an older database * will cause this entry to be overwritten. * * @param string $key ID for the database * @param string $dsn DSN for the database * @param string $user User for connection * @param NULL|string $pass Password for connection * @param bool $frozen Whether this database is frozen or not * * @return void */ public static function addDatabase($key, $dsn, $user = NULL, $pass = NULL, $frozen = FALSE, $autoSetEncoding = TRUE) { self::$toolboxes[$key] = RedBean_Setup::kickstart($dsn, $user, $pass, $frozen, $autoSetEncoding); }
print "[" . $tests . "]"; } function fail() { printtext("FAILED TEST"); debug_print_backtrace(); exit; } function testpack($name) { printtext("testing: " . $name); } //INCLUDE YOUR REDBEAN FILE HERE! require "rb.php"; //require("RedBean/redbean.inc.php"); $toolbox = RedBean_Setup::kickstart("pgsql:host={$ini['pgsql']['host']} dbname={$ini['pgsql']['schema']}", $ini['pgsql']['user'], $ini['pgsql']['pass']); function droptables() { global $toolbox; foreach ($toolbox->getWriter()->getTables() as $t) { try { $toolbox->getDatabaseAdapter()->Exec("drop table \"{$t}\" cascade"); } catch (Exception $e) { } } } //Observable Mock Object class ObservableMock extends RedBean_Observable { public function test($eventname, $info) {
/** * @param string $dsn * @return RedBean_ToolBox $toolbox */ public static function kickstartDevL($dsn) { self::checkDSN($dsn); $pdo = new RedBean_Driver_PDO($dsn, "", ""); $adapter = new RedBean_Adapter_DBAdapter($pdo); $writer = new RedBean_QueryWriter_SQLite($adapter, false); $redbean = new RedBean_OODB($writer); $toolbox = new RedBean_ToolBox($redbean, $adapter, $writer); //deliver everything back in a neat toolbox self::$toolbox = $toolbox; return self::$toolbox; }
public static function failedTest() { die("<b style='color:red'>FAIL</b>"); } public static function test($value, $expected) { if ($value != $expected) { die("<b style='color:red'>FAIL</b>"); } else { self::instance()->progress(); } } } //Use this database for tests require "oodb.php"; RedBean_Setup::kickstart("mysql:host=localhost;dbname=oodb", "root", "", false, "innodb", false); SmartTest::instance()->testPack = "Basic test suite"; $tests = 0; SmartTest::instance()->progress(); //Test description: Does the redbean core class exist? if (class_exists("RedBean_OODB")) { SmartTest::instance()->progress(); } else { SmartTest::failedTest(); } //Test description: Does the redbean decorator class exist? if (class_exists("RedBean_Decorator")) { SmartTest::instance()->progress(); } else { SmartTest::failedTest(); }
printtext("FAILED TEST"); debug_print_backtrace(); exit; } function testpack($name) { printtext("testing: " . $name); } //Test the Setup Class testpack("Test Setup"); //Can we load all modules properly? //INCLUDE YOUR REDBEAN FILE HERE! require "rb.php"; //require("RedBean/redbean.inc.php"); //Test whether we can setup a connection $toolbox = RedBean_Setup::kickstart("sqlite:{$ini['sqlite']['file']}"); //prepare... empty the database foreach ($toolbox->getWriter()->getTables() as $table) { $sql = "DROP TABLE `" . $table . "`"; $toolbox->getDatabaseAdapter()->exec($sql); } //check whether we emptied the database correctly... asrt(count($toolbox->getWriter()->getTables()), 0); /** * Observable Mock * This is just for testing */ class ObservableMock extends RedBean_Observable { public function test($eventname, $info) {
/** * Generic Kickstart method. * This is the generic kickstarter. It will establish a database connection * using the $dsn, the $username and the $password you provide. * If $frozen is boolean TRUE it will start RedBean in frozen mode, meaning * that the database cannot be altered. If RedBean is started in fluid mode * it will adjust the schema of the database if it detects an * incompatible bean. * This method returns a RedBean_Toolbox $toolbox filled with a * RedBean_Adapter, a RedBean_QueryWriter and most importantly a * RedBean_OODB; the object database. To start storing beans in the database * simply say: $redbean = $toolbox->getRedBean(); Now you have a reference * to the RedBean object. * Optionally instead of using $dsn you may use an existing PDO connection. * Example: RedBean_Setup::kickstart($existingConnection, true); * * @param string|PDO $dsn Database Connection String * @param string $username Username for database * @param string $password Password for database * @param boolean $frozen Start in frozen mode? * * @return RedBean_ToolBox $toolbox */ public static function kickstart($dsn, $username = NULL, $password = NULL, $frozen = false) { if ($dsn instanceof PDO) { $pdo = new RedBean_Driver_PDO($dsn); $dsn = $pdo->getDatabaseType(); } else { self::checkDSN($dsn); $pdo = new RedBean_Driver_PDO($dsn, $username, $password); } $adapter = new RedBean_Adapter_DBAdapter($pdo); if (strpos($dsn, "pgsql") === 0) { $writer = new RedBean_QueryWriter_PostgreSQL($adapter); } else { if (strpos($dsn, "sqlite") === 0) { $writer = new RedBean_QueryWriter_SQLiteT($adapter); } else { $writer = new RedBean_QueryWriter_MySQL($adapter); } } $redbean = new RedBean_OODB($writer); if ($frozen) { $redbean->freeze(true); } $toolbox = new RedBean_ToolBox($redbean, $adapter, $writer); //deliver everything back in a neat toolbox self::$toolbox = $toolbox; return self::$toolbox; }
/** * Returns a collection of Domain Objects. * @param string $type * @param string $query * @return array $collection */ public static function getDomainObjects($type, $query = "1", $values = array()) { //Fetch us a toolbox. $tools = RedBean_Setup::getToolBox(); $redbean = $tools->getRedBean(); $domainObject = new $type(); $typeName = $domainObject->bean->getMeta("type"); $collection = array(); $finder = new \RedBean_Plugin_Finder(); $beans = $finder->where($typeName, $query, $values); foreach ($beans as $bean) { $domainObject = new $type(); $domainObject->bean = $bean; $collection[] = $domainObject; } return $collection; }
} //If you did not specify a username, we do this for you if (!isset($username)) { $username = "******"; } //If you did not specify a database type, we will use mysql if (!isset($typeofdatabase)) { $typeofdatabase = "mysql"; } //Assemble a database connection string (DSN) $dsn = "{$typeofdatabase}:host=localhost;dbname={$database}"; //Connect to database and fetch the toolbox; either with or without password if (!isset($password)) { $toolbox = RedBean_Setup::kickstartDev($dsn, $username); } else { $toolbox = RedBean_Setup::kickstartDev($dsn, $username, $password); } //Extracting tools for you $redbean = $toolbox->getRedBean(); $db = $toolbox->getDatabaseAdapter(); $writer = $toolbox->getWriter(); //Creating an Association Manager for you $assoc = new RedBean_AssociationManager($toolbox); //Creating a Tree Manager for you $tree = new RedBean_TreeManager($toolbox); function assoc($bean1, $bean2) { global $assoc; $assoc->associate($bean1, $bean2); //also put a cascaded delete constraint - why not? RedBean_Plugin_Constraint::addConstraint($bean1, $bean2);
/** * Kickstart for development phase (strict mode). * Use this method to quickly setup RedBean for use during development phase. * This Kickstart establishes a database connection * using the $dsn, the $username and the $password you provide. * It will start RedBean in fluid mode; meaning the database will * be altered if required to store your beans. * This method returns a RedBean_Toolbox $toolbox filled with a * RedBean_Adapter, a RedBean_QueryWriter and most importantly a * RedBean_OODB; the object database. To start storing beans in the database * simply say: $redbean = $toolbox->getRedBean(); Now you have a reference * to the RedBean object. * @param string $dsn * @param string $username * @param string $password * @return RedBean_ToolBox $toolbox */ public static function kickstartDevS($dsn, $username = "******", $password = "") { $frozen = false; self::checkDSN($dsn); $pdo = new RedBean_Driver_PDO($dsn, $username, $password); $adapter = new RedBean_Adapter_DBAdapter($pdo); $writer = new RedBean_QueryWriter_MySQLS($adapter, $frozen); $redbean = new RedBean_OODB($writer); $toolbox = new RedBean_ToolBox($redbean, $adapter, $writer); //deliver everything back in a neat toolbox self::$toolbox = $toolbox; return self::$toolbox; }
} catch (RedBean_Exception_FailedAccessBean $e) { fail(); } //Test whether we can pre-open, or prelock multiple beans at once and //if the logger fires less queries testpack("Test Preloader"); class QueryCounter implements RedBean_Observer { public $counter = 0; public function onEvent($event, $info) { $this->counter++; } } $querycounter = new QueryCounter(); $observers = RedBean_Setup::getAttachedObservers(); asrt($logger instanceof RedBean_Observer, true); $pagea = $redbean->dispense("page"); $pageb = $redbean->dispense("page"); $pagec = $redbean->dispense("page"); $paged = $redbean->dispense("page"); $redbean->store($pagea); $redbean->store($pageb); $redbean->store($pagec); $redbean->store($paged); $a->associate($pagea, $pageb); $a->associate($pagea, $pagec); $a->associate($pagea, $paged); $ids = $a->related($pagea, "page"); $adapter->exec("TRUNCATE __log"); $adapter->addEventListener("sql_exec", $querycounter);
<?php /* init.php Redbean initializator Mochammad Masbuchin */ require "RedBean/redbean.inc.php"; $toolbox = RedBean_Setup::kickstartDev("mysql:host=localhost;dbname=restobean", "root", ""); $redbean = $toolbox->getRedBean(); $pegawai = $redbean->dispense("pegawai"); $menu = $redbean->dispense("menu"); $cashierin = $redbean->dispense("cashierin"); $cashierout = $redbean->dispense("cashierout"); $order = $redbean->dispense("order"); $ordermenu = $redbean->dispense("ordermenu"); $settle = $redbean->dispense("settle"); $bahan = $redbean->dispense("bahan"); $stockhistory = $redbean->dispense("stockhistory"); $resep = $redbean->dispense("resep"); $keuangan = $redbean->dispense("keuangan"); $payout = $redbean->dispense("payout"); $adapter = $toolbox->getDatabaseAdapter(); //$meja->import($lesehan, "namameja, jumlahkursi, status, lokasi"); /*$meja->import($pendopo, "namameja, jumlahkursi, status, lokasi"); print_r($meja);*/
public function testDateTimeHinting() { $toolbox = RedBean_Setup::kickstart(Yii::app()->db->connectionString, Yii::app()->db->username, Yii::app()->db->password); R::exec("drop table if exists bean"); // Not Coding Standard $bean = R::dispense("bean"); // Not Coding Standard $bean->setMeta("hint", array("prop" => "datetime")); // Not Coding Standard $bean->prop = "2010-01-01 10:00:00"; // Not Coding Standard R::store($bean); // Not Coding Standard $rows = R::getAll('desc bean'); $this->assertEquals('prop', $rows[1]['Field']); $this->assertEquals('datetime', $rows[1]['Type']); }