/** * Quotes primitive value with its primitve variable (alias.var) * @param mixed $v * @param string $pvar * @return true|string (error message if string) */ private function _qq(&$v, &$pvar) { // unquote pvar $pvar_ = $this->uq($pvar); // split primitive var to alias and var list($alias, $var) = explode('.', $pvar_); if (!$alias || !$var) { return "Invalid primitive variable [{$pvar}]"; } // get the class for alias if (!($class = $this->aliases[$alias])) { return "No class found for alias [{$alias}]"; } // get class map if (!($cm = $this->em->getClassMap($class))) { return "No class map for [{$class}]"; } // is var 'oid'? if ($var == 'oid') { // replace var name with column name $pvar = $this->qid($alias) . '.' . $this->qid($cm->getOidColumn()); } else { // get field map (for non-oid field) if (!($fm = $cm->getField($var))) { return "No field map for [{$class}::{$var}]"; } // replace var name with column name $pvar = $this->qid($alias) . '.' . $this->qid($fm->getColumnName()); // quote value $v = $this->q($v, $fm); } return true; }
/** * Load configuration from a file and set it to the EZPDO manager. * * If config file is not specified, it tries to load config.xml first. * Then config.ini if config.xml not found from the current directory. * * @param string $file * @return bool */ function epLoadConfig($file = false) { // use default config file? if (!$file) { // try config.ini first if (file_exists($file = 'config.ini')) { $file = 'config.ini'; } else { if (file_exists('config.xml')) { $file = 'config.xml'; } else { return false; } } } else { // check if the specified config file exists if (!file_exists($file)) { return false; } } // load the config file include_once EP_SRC_BASE . '/epConfig.php'; if (!($cfg =& epConfig::load($file))) { return false; } // set config to the EZPDO manager return epManager::instance()->setConfig($cfg); }
function initPersistance() { $m = epManager::instance(); $m->setConfigOption("compiled_dir", "" . $this->config['Paths']['cache'] . $this->config['Models']['cached']); $m->setConfigOption("source_dirs", "" . $this->config['Models']['folder']); $m->setConfigOption("log_file", "" . $this->config['Paths']['logs'] . "ezpdo.log"); foreach ($this->config['Persistance'] as $k => $v) { $m->setConfigOption($k, $v); } $this->db = $m; }
/** * setup before each test * @param string $dbal (adodb or peardb) * @param string $db (mysql, pgsql, or sqlite) */ function _setUp($dbal, $db) { // destroy singletons $this->_destroy(); // load config.xml for compiler include_once EP_SRC_BASE . '/epConfig.php'; $cfg =& epConfig::load(dirname(__FILE__) . "/config.xml"); $this->assertTrue(!empty($cfg)); // set dblib $cfg->set('db_lib', $dbal); // make input/output path absolute (fixed) $source_dirs = EP_TESTS . '/classes/'; $cfg->set('source_dirs', $source_dirs); // set compiled dir switch ($db) { case 'mysql': $compiled_file = $cfg->get('test/compiled_file/mysql'); $default_dsn = $cfg->get('test/default_dsn/mysql'); break; case 'pgsql': $compiled_file = $cfg->get('test/compiled_file/pgsql'); $default_dsn = $cfg->get('test/default_dsn/pgsql'); $cfg->set('default_oid_column', 'eoid'); // oid is special in pgsql break; case 'sqlite': $compiled_file = $cfg->get('test/compiled_file/sqlite/' . $dbal); $default_dsn = $cfg->get('test/default_dsn/sqlite/' . $dbal); break; } $cfg->set('compiled_file', $compiled_file); $cfg->set('default_dsn', $default_dsn); // force compile so default_dsn gets into class map $cfg->set('force_compile', true); // get epManager instance include_once EP_SRC_RUNTIME . '/epManager.php'; $this->m = null; // force a new instance $this->m =& epManager::instance(); $this->assertTrue($this->m); // set config to manager $this->assertTrue($this->m->setConfig($cfg)); // assert source_dirs is correct $this->assertTrue($this->m->getConfigOption('source_dirs') === $source_dirs); // assert source_dirs is correct $this->assertTrue($this->m->getConfigOption('compiled_file') === $compiled_file); // assert default_dsn is correct $this->assertTrue($this->m->getConfigOption('default_dsn') === $default_dsn); }
/** * Test serialization on an array of objects */ function testSerialization() { $this->_setUp('adodb', 'sqlite'); // make sure we have setup manager $this->assertTrue($this->m); include_once EP_TESTS . '/classes/inverses/src/eptInvOneManyA.php'; include_once EP_TESTS . '/classes/inverses/src/eptInvOneManyB.php'; // create eptInvOneA and eptInvOneB $this->assertTrue($a = $this->m->create('eptInvOneManyA')); $this->assertTrue($b = $this->m->create('eptInvOneManyB')); // set $a to $b->a $b->a = $a; $this->assertTrue($b->a === $a); $this->assertTrue($a->bs->inArray($b)); // keep the dump string of the objects $this->assertTrue($a_str = $a->__toString()); $this->assertTrue($b_str = $b->__toString()); // put $a1 and $b1 into an array $array = array($a, $b); $this->assertTrue(count($array) == 2); // --- serailize array --- $this->assertTrue($serialized = serialize($array)); // --- unserailize array --- $this->assertTrue($array_unserialized = unserialize($serialized)); // make sure two objects only $this->assertTrue(count($array_unserialized) == 2); // get a and b $this->assertTrue($a_u = $array_unserialized[0]); $this->assertTrue($b_u = $array_unserialized[1]); // check if association is kept $this->assertTrue($b_u->a === $a_u); $this->assertTrue($a_u->bs->inArray($b_u)); // check if string dump matches $this->assertTrue($a_u->__toString() == $a_str); $this->assertTrue($b_u->__toString() == $b_str); }
/** * Dump queries * @return void */ function dumpQueries() { $m = epManager::instance(); $db_queries = $m->getQueries(); foreach ($db_queries as $db => $queries) { echo "*** database: {$db} (" . count($queries) . ")***\n"; if ($queries) { // remove "\n" $s = ''; foreach ($queries as &$q) { $q = str_replace("\n", '', $q); $s .= $q . "\n"; } echo $s; } } }
/** * Returns one or more EnumeratedValue instances as a multi-valued array. * If the $enumType parameter is given, the result set will be limited * to the named scope. If the $enumValue parameter is given, only matching * instance(s) will be returned. * * @param string enumType The enum type (e.g. PublicationState, EventStatus, ProgramType, ResourceType) * @param string value A specific enum value * @return Zero or more EnumeratedValues as an array keyed by enum type */ function fetch($enumType = null, $enumValue = null) { global $logger; $logger->debug(get_class($this) . "::fetch({$enumType}, {$enumValue})"); $pdo = epManager::instance(); $result = array(); if ($enumType == null) { $enumeratedValues = $pdo->find('from EnumeratedValue order by oid'); } else { $enumeratedValues = $pdo->find('from EnumeratedValue where scope = ? order by oid', $enumType); } foreach ($enumeratedValues as $value) { if ($enumValue == null || $enumValue == $value->getValue()) { $result[$value->getScope()][] = $value; } } return $result; }
/** * Initialize categories */ function initCategories() { // define initial setup values $categories = array("Genre" => array(array("name" => "Theater", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Readings and Talks", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Cinema's Legacy", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Film", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Comedy", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Food", "subtitle" => "", "description" => "", "pubState" => "Published")), "Audience" => array(array("name" => "Family", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Teen", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Toddler", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Public", "subtitle" => "", "description" => "", "pubState" => "Published")), "Series" => array(array("name" => "Sunset Concerts", "subtitle" => "", "description" => "", "pubState" => "Published"), array("name" => "Cinema Z", "subtitle" => "", "description" => "", "pubState" => "Published"))); $pdo = epManager::instance(); // cleanup/setup enumerations foreach ($categories as $class => $elements) { $filter = $pdo->create($class); $values = $pdo->find($filter); foreach ($values as $item) { $pdo->delete($item); } for ($index = 0; $index < count($elements); $index++) { $category = $pdo->create($class); $category->setName($elements[$index]["name"]); $category->setSubtitle($elements[$index]["subtitle"]); $category->setDescription($elements[$index]["description"]); $category->setPubState($elements[$index]["pubState"]); $pdo->commit($category); } } }
function setUp() { $this->pdo = epManager::instance(); }
/** * Makes a cache key for a class * * Since EZPDO allows a user to change database (DSN) at runtime (see * {@link epManager::setDsn()}), it is important to use the current * DSN of the class in generating the cache key. * * @param string $class The class name * @param string $extra The extra string (mostly for locking type) * @return false|string */ protected function _key($class, $extra = '') { if (!($cm =& self::$em->getClassMap($class))) { return false; } if (!($dsn = $cm->getDsn())) { return false; } return md5($dsn . $class . $extra); }
/** * Prepare database if not exists * @param string $class * @param string $rtable (relationship table, only used if class is epObjectRelation) * @return boolean */ public function prepareDb($class, $rtable = false) { // if relation table is given, set it to runtime manager if ($rtable) { self::$em->setRelationTable($rtable); } // get class map for class if (!($cm = self::$em->getClassMap($class))) { return false; } // no table for abstract class if ($cm->isAbstract()) { return true; } return self::$db->create($cm); }
/** * Implement {@link epSingleton} interface * Forcefully destroy old instance (only used for tests). * After reset(), {@link instance()} returns a new instance. */ public static function destroy() { self::$instance = null; }
/** * Return the PublicationState PDO for the given value * @access private * @param string The PublicationSatte value * @return PublicationState PDO */ private function fetchPubState($value) { global $logger; $logger->debug(get_class($this) . "::fetchPubState({$value})"); if (is_string($value)) { $pdo = epManager::instance(); $template = $pdo->create('PublicationState'); $template->setValue($value); $pubStates = $pdo->find($template); if (count($pubStates) > 0) { return $pubStates[0]; } else { $logger->debug("No PublicationStates matched value: {$value}"); return false; } } }
/** * Returns the PDO object for the given scope. */ private function fetch($scope) { global $logger; $logger->debug(get_class($this) . "::fetch({$scope})"); $epm = epManager::instance(); $pdos = $epm->find('from Announcement where scope = ?', $scope); return $pdos[0]; }
* * @author Oak Nauhygon <*****@*****.**> * @version $Revision: 991 $ $Date: 2006-05-31 15:24:19 -0400 (Wed, 31 May 2006) $ * @package ezpdo_ex * @subpackage ezpdo_ex.bookstore */ /** * Need EZPDO runtime API */ include_once dirname(__FILE__) . '/../../ezpdo_runtime.php'; /** * This script prints out all authors and books stored in database * and can be called by other scripts to print all records. */ // get the persistence manager $m = epManager::instance(); // get all authors $authors = $m->get('Author'); // print all authors if ($authors) { foreach ($authors as $a) { //echo $a->toString() . "\n"; echo $a; echo "\n"; } } else { echo "No author is found.\n"; } // get all books $books = $m->get('Book'); // print all books
/** * Returns the timestamp for the first scheduled start time * * @access private * @return int Timestamp of first scheduled startTime (min) */ private function getFirstScheduled() { global $logger; $logger->debug(get_class($this) . "::getFirstScheduled()"); $epm = epManager::instance(); $first = $epm->find("min(startTime) from Schedule where startTime > 0"); $logger->debug("First scheduled timestamp: " . $first); return $first; }
/** * Converts the last record set into epObject object(s) with class map * @param epClassMap $cm the class map for the conversion * @param array (of integers) object ids to be excluded * @return false|array (of epObject) * @throws epExceptionDbObject */ protected function _rs2obj($cm, $oids_ex = null) { // !!!important!!! with a large db, the list of oid to be excluded // $oids_ex can grown really large and can significantly slow down // queries. so it is suppressed in the select statement and moved // to this method to process. // get epManager instance and cache it if (!$this->ep_m) { $this->ep_m =& epManager::instance(); } // get the class name $class = $cm->getName(); // get all mapped vars if (!($fms = $cm->getAllFields())) { return self::$false; } // reset counter and return value $ret = array(); // go through reach record $okay = $this->db->rsRestart(); while ($okay) { // get oid column $oid = $this->db->rsGetCol($cn = $cm->getOidColumn(), $class . '.' . $cn); // exclude it? if ($oids_ex && in_array($oid, $oids_ex)) { // next row $okay = $this->db->rsNext(); // exclude it continue; } // call epManager to create an instance (false: no caching; false: no event dispatching) if (!($o =& $this->ep_m->_create($class, false, false))) { // next row $okay = $this->db->rsNext(); continue; } // go through each field foreach ($fms as $fname => $fm) { // skip non-primivite field if (!$fm->isPrimitive()) { continue; } // get var value and set to object $val = $this->db->rsGetCol($cn = $fm->getColumnName(), $class . '.' . $cn); // set value to var (true: no dirty flag change) $o->epSet($fm->getName(), $this->_castType($val, $fm->getType()), true); } // set oid $o->epSetObjectId($oid); // collect return result $ret[] = $o; // next row $okay = $this->db->rsNext(); } return $ret; }
/** * Copies the updated values of the bean to the pdo * object, then commits the pdo object to update the * address. * * @access private * @param bean Address Bean * @return pdo updated Address PDO */ private function updateAddress($bean) { global $logger; $logger->debug(get_class($this) . "::updateAddress({$bean})"); $logger->debug("Address is of class: " . get_class($bean)); $logger->debug("Before update the address id: " . $bean->getOid()); $epm = epManager::instance(); $pdo = null; if ($bean->getOid() > 0) { $pdo = $this->fetchAddressById($bean->getOid()); $logger->debug("Oid > 0: " . $pdo->getOid()); } else { if (trim($bean->getStreet()) != NULL) { $pdo = $epm->create('Address'); $logger->debug("No oid, but valid street: " . $bean->getStreet()); } else { return null; // This is not a valid address } } $pdo = BeanUtil::copyBean($bean, $pdo); $pdo = $epm->commit($pdo); $logger->debug("After update the address id: " . $pdo->getOid()); return $pdo; }
function _testQuery56() { $this->assertTrue($m = epManager::instance()); $this->assertTrue($os = $m->query("from eptAuthor as a where a.name in (?) order by name", array('Richard Helm', 'Erich Gamma'))); $this->assertTrue(count($os) == 2); $this->assertTrue($os[0]->name == 'Erich Gamma'); $this->assertTrue($os[1]->name == 'Richard Helm'); return true; }
/** * Check if the object is valid * * Implements the {@link epValidateable} interface * @param bool $recursive (ignored) * @return true|string (error msg) */ public function isValid($recursive) { // array to hold errors $errors = array(); // get the manager if (!($m = epManager::instance())) { $errors[] = 'cannot get manager'; return $errors; } // // check object a // if (!$this->class_a) { $errors[] = 'class_a is empty'; } if (!$this->oid_a) { $errors[] = 'oid_a is zero (invalid oid) or empty'; } if (!$this->var_a) { $errors[] = 'var_a is empty'; } // check if object a if ($this->class_a) { // check if class a exists if (!($cm = $m->getClassMap($this->class_a))) { $errors[] = 'class_a [' . $this->class_a . '] no longer exists'; } else { // check if var_a exists if ($this->var_a) { if (!$cm->getField($this->var_a)) { $errors[] = 'var_a [' . $this->var_a . '] no longer exists in class_a [' . $this->class_a . ']'; } } // check if object_a exists if (!($obj_a = $m->get($this->class_a, $this->oid_a))) { $errors[] = 'object of class_a [' . $this->class_a . '] with oid [' . $this->oid_a . '] no longer exists'; } } } // // check object b // if (!$this->base_b) { $errors[] = 'base_b is empty'; } else { // check if base_b exists if (!($cm = $m->getClassMap($this->base_b))) { $errors[] = 'base_b [' . $this->base_b . '] no longer exists'; } } if (!$this->class_b) { $errors[] = 'class_b is empty'; } if (!$this->oid_b) { $errors[] = 'oid_b is zero (invalid oid) or empty'; } // check if object b if ($this->class_b) { // check if class b exists if (!($cm = $m->getClassMap($this->class_b))) { $errors[] = 'class_b [' . $this->class_b . '] no longer exists'; } else { // check if object_b exists if (!($obj_b = $m->get($this->class_b, $this->oid_b))) { $errors[] = 'object of class_b [' . $this->class_b . '] with oid [' . $this->oid_b . '] no longer exists'; } } } // either return array of errors or true return $errors ? $errors : true; }
/** * Implement magic method __toString() * * This method can be handily used for debugging purpose. * Simply use "echo" to dump the object's info. * * @return string */ public function __toString() { // indentation $indent = ' '; // the output string $s = ''; // class for the object $s .= 'object (' . $this->epGetClassMap()->getName() . ')' . "\n"; // object id $s .= $indent . 'oid : ' . $this->epGetObjectId() . "\n"; // object uid $s .= $indent . 'uid : ' . $this->epGetUId() . "\n"; // dirty flag $s .= $indent . 'is dirty? : '; if ($this->epIsDirty()) { $s .= 'yes'; } else { $s .= 'no'; } $s .= "\n"; // dirty flag $s .= $indent . 'is committable? : '; if ($this->epIsCommittable()) { $s .= 'yes'; } else { $s .= 'no'; } $s .= "\n"; // delete flag $s .= $indent . 'is deleted? : '; if ($this->epIsDeleted()) { $s .= 'yes'; } else { $s .= 'no'; } $s .= "\n"; // vars $vars = $this->epGetVars(); // go through each var from the example object $s .= $indent . 'vars' . "\n"; $indent .= $indent; foreach ($vars as $var => $value) { // skip oid if ($var == 'oid') { continue; } // output var name $s .= $indent . '[' . $var . ']: '; // re-get value so objects are loaded $value = $this->epGet($var); if ($value instanceof epObject) { $s .= $this->ep_m->encodeUoid($value); } else { if ($value instanceof epArray) { $s .= $value->getClass() . '(' . $value->count() . ')'; } else { $s .= print_r($value, true); } } $s .= "\n"; } // return the string return $s; }
/** * Returns a PDO instance for the target Category. Currently * all subclasses of Category are managed in the same PDO table. * Therefore, the scope is not actually needed. Adding it to the * API however will allow for the separation of these subsclasses * if required in the future. * * @param string scope The category type (e.g. Audience, Genre) * @param int $oid The oid of the target category * @return pdo The Category PDO */ private function fetchCategoryById($scope, $oid) { $pdo = epManager::instance(); $cat = $pdo->get('Category', $oid); if ($cat === FALSE) { trigger_error("Invalid Category: {$oid} not found", E_USER_ERROR); return; } if (is_array($cat)) { trigger_error("Invalid Category: ambiguous results for {$oid}", E_USER_ERROR); return; } return $cat; }
<?php require_once dirname(__FILE__) . '/../../library/ezpdo/ezpdo_runtime.php'; require_once dirname(__FILE__) . '/../_orm/orm.inc.php'; epLoadConfig(dirname(__FILE__) . '/config.ini'); try { $myManager = epManager::instance(); } catch (PDOException $e) { echo $e->getMessage(); }