public function get($connection, $prefix = 'cms') { $paths = array(realpath(__DIR__ . '/../Entity')); $isDevMode = false; $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, null, null, false); $eventManager = new \Doctrine\Common\EventManager(); $tablePrefix = new Prefix($prefix); $eventManager->addEventListener(Events::loadClassMetadata, $tablePrefix); return EntityManager::create($connection, $config, $eventManager); }
protected function createEntityManager() { $config = new \Doctrine\ORM\Configuration(); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver()); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('DoctrineExtensions\\PHPUnit\\Proxies'); $eventManager = new \Doctrine\Common\EventManager(); $eventManager->addEventListener(array("preTestSetUp", "postTestSetUp"), $this); $conn = array('driver' => 'pdo_sqlite', 'memory' => true); return \Doctrine\ORM\EntityManager::create($conn, $config, $eventManager); }
public static function create(DI\Container $container) { $config = new \Doctrine\ORM\Configuration(); $cache = new \Doctrine\Common\Cache\ArrayCache(); $config->setMetadataCacheImpl($cache); $driverImpl = $config->newDefaultAnnotationDriver($container->params['appDir'] . '/models/Entities'); $config->setMetadataDriverImpl($driverImpl); $config->setQueryCacheImpl($cache); $config->setProxyDir($container->params['tempDir'] . '/Proxies'); $config->setProxyNamespace('Tatami\\Proxies'); $config->setAutoGenerateProxyClasses(true); /* if ($container->params['productionMode'] == true) { $config->setAutoGenerateProxyClasses(true); } else { $config->setAutoGenerateProxyClasses(false); } var_dump() * */ try { $dbConfig = $container->params['database']; if ($dbConfig['prefix'] != '') { $evm = new \Doctrine\Common\EventManager(); // Table Prefix $tablePrefix = new \DoctrineExtensions\TablePrefix($dbConfig['prefix']); $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); $em = EntityManager::create($dbConfig, $config, $evm); } else { $em = EntityManager::create($dbConfig, $config); } $validator = $container->getService('validator'); $em->setValidator($validator); return $em; } catch (PDOException $e) { echo $e->getMessage(); } catch (\Doctrine\DBAL\DBALException $e) { echo $e->getMessage(); } }
public static function init() { $instance = self::getInstance(); $conf = self::conf(); require_once $conf->root_dir . '/system/lib/Doctrine/Common/ClassLoader.php'; // Set up class loading $classLoader = new \Doctrine\Common\ClassLoader('Doctrine', $conf->root_dir . '/system/lib'); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Doctrine\\ORM', realpath(__DIR__ . '/../../lib')); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Doctrine\\DBAL', realpath(__DIR__ . '/../../lib/vendor/doctrine-dbal/lib')); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Doctrine\\Common', realpath(__DIR__ . '/../../lib/vendor/doctrine-common/lib')); $classLoader->register(); // Set up caches $config = new \Doctrine\ORM\Configuration(); $cache = new \Doctrine\Common\Cache\ArrayCache(); $config->setMetadataCacheImpl($cache); $driverImpl = $config->newDefaultAnnotationDriver(array($conf->root_dir . '/system/Entities')); $config->setMetadataDriverImpl($driverImpl); $config->setQueryCacheImpl($cache); // Proxy configuration $config->setProxyDir($conf->root_dir . '/system/models'); $config->setProxyNamespace('Proxies'); // Set up logger // $logger = new EchoSQLLogger; // $config->setSQLLogger($logger); $config->setAutoGenerateProxyClasses(true); // Database connection information $connectionParams = array('dbname' => $conf->db_name, 'user' => $conf->db_username, 'password' => $conf->db_password, 'host' => $conf->db_hostname, 'driver' => 'pdo_' . $conf->db_driver, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'); // Create EntityManager $instance->db = \Doctrine\ORM\EntityManager::create($connectionParams, $config); // Table Prefix $evm = new \Doctrine\Common\EventManager(); $tablePrefix = new \Doctrine\Extensions\TablePrefix($conf->db_prefix); $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); // Create EntityManager $instance->em = \Doctrine\ORM\EntityManager::create($connectionParams, $config, $evm); }
$driverImpl = new \Doctrine\ORM\Mapping\Driver\YamlDriver(ASCMS_MODEL_PATH . '/yml'); $chainDriverImpl->addDriver($driverImpl, 'Cx\\Model'); $driverImpl = new \Doctrine\ORM\Mapping\Driver\YamlDriver(ASCMS_CORE_PATH . '/ContentManager/Model/Yaml'); $chainDriverImpl->addDriver($driverImpl, 'Cx\\Core\\ContentManager'); //loggable stuff $loggableDriverImpl = $config->newDefaultAnnotationDriver(array(UPDATE_CORE, $doctrineDir . 'Gedmo/Loggable/Entity')); $chainDriverImpl->addDriver($loggableDriverImpl, 'Gedmo\\Loggable'); $loggableListener = new \Cx\Update\core\LoggableListener(); $evm->addEventSubscriber($loggableListener); \Env::set('loggableListener', $loggableListener); //tree stuff $treeListener = new \Gedmo\Tree\TreeListener(); $evm->addEventSubscriber($treeListener); $config->setMetadataDriverImpl($chainDriverImpl); //table prefix $prefixListener = new \DoctrineExtension\TablePrefixListener($_DBCONFIG['tablePrefix']); $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $prefixListener); //page listener for unique slugs $pageListener = new PageEventListener(); $evm->addEventListener(\Doctrine\ORM\Events::preUpdate, $pageListener); $evm->addEventListener(\Doctrine\ORM\Events::onFlush, $pageListener); $evm->addEventListener(\Doctrine\ORM\Events::postPersist, $pageListener); $evm->addEventListener(\Doctrine\ORM\Events::preRemove, $pageListener); $config->setSqlLogger(new \Cx\Lib\DBG\DoctrineSQLLogger()); $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config, $evm); //resolve enum, set errors $conn = $em->getConnection(); $conn->setCharset($_DBCONFIG['charset']); $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); $conn->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string'); Env::setEm($em);
/** * Initialize auto loader of Doctrine. * * @return \Doctrine\ORM\EntityManager */ public static function init($config) { self::optionsContainDSN($config); $vendor = VENDOR_PATH . '/doctrine/common/lib/'; // ensure doctrine2 exists in the libraries folder if (is_file($vendor . 'Doctrine/Common/ClassLoader.php') === false) { throw new \Koch\Exception\Exception('Doctrine2 not found. Check Libraries Folder.', 100); } // get isolated loader require $vendor . 'Doctrine/Common/ClassLoader.php'; // setup autoloaders with namespace and path to search in $classLoader = new \Doctrine\Common\ClassLoader('Doctrine', VENDOR_PATH); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Symfony', VENDOR_PATH . 'Doctrine/Symfony'); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Entity', APPLICATION_PATH . 'Doctrine'); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Repository', APPLICATION_PATH . 'Doctrine'); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Proxy', APPLICATION_PATH . 'Doctrine'); $classLoader->register(); // include Doctrine Extensions $classLoader = new \Doctrine\Common\ClassLoader('doctrine-extensions', VENDOR_PATH . 'gedmo/doctrine-extensions/lib/Gedmo'); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('DoctrineExtensions', VENDOR_PATH . 'beberlei/DoctrineExtensions/lib'); $classLoader->register(); // fetch doctrine config handler for configuring $D2Config = new \Doctrine\ORM\Configuration(); // fetch cache driver - APC in production and Array in development mode if (extension_loaded('apc') and DEBUG === false) { $cache = new \Doctrine\Common\Cache\ApcCache(); } else { $cache = new \Doctrine\Common\Cache\ArrayCache(); } // set cache driver $D2Config->setMetadataCacheImpl($cache); $D2Config->setQueryCacheImpl($cache); // set annotation driver for entities $D2Config->setMetadataDriverImpl($D2Config->newDefaultAnnotationDriver(self::getModelPathsForAllModules())); /* * This is slow like hell, because getAllClassNames traverses all * dirs and files and includes them. Its a workaround, till i find * a better way to acquire all the models. * @todo optimize this for performance reasons */ $D2Config->getMetadataDriverImpl()->getAllClassNames(); #\Koch\Debug\Debug::firebug($config->getMetadataDriverImpl()->getAllClassNames()); // set proxy dirs $D2Config->setProxyDir(APPLICATION_PATH . 'Doctrine'); $D2Config->setProxyNamespace('Proxy'); // regenerate proxies only in debug and not in production mode if (DEBUG === true) { $D2Config->setAutoGenerateProxyClasses(true); } else { $D2Config->setAutoGenerateProxyClasses(false); } // use main configuration values for setting up the connection $connectionOptions = ['driver' => $config['database']['driver'], 'user' => $config['database']['user'], 'password' => $config['database']['password'], 'dbname' => $config['database']['dbname'], 'host' => $config['database']['host'], 'charset' => $config['database']['charset'], 'driverOptions' => ['charset' => $config['database']['charset']]]; // set up Logger #$config->setSqlLogger(new \Doctrine\DBAL\Logging\EchoSqlLogger); /* * Events */ $event = new \Doctrine\Common\EventManager(); /* * Database Prefix * * The constant definition is for building (raw) sql queries manually. * The database prefixing is registered via an event. */ define('DB_PREFIX', $config['database']['prefix']); $tablePrefix = new TablePrefix(DB_PREFIX); $event->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); /* * Custom Functions * * We need some more functions for MySQL, like RAND for random values. */ $D2Config->addCustomNumericFunction('RAND', 'Koch\\Doctrine\\Extensions\\Query\\Mysql\\Rand'); // Entity manager $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $D2Config, $event); // set DBAL DebugStack Logger (also needed for counting queries) if (defined('DEBUG') and DEBUG === 1) { self::$sqlLoggerStack = new \Doctrine\DBAL\Logging\DebugStack(); $em->getConfiguration()->setSQLLogger(self::$sqlLoggerStack); // Echo SQL Queries directly on the page. $em->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); } self::$em = $em; // the D2 initalization is done, remove vars to safe memory unset($config, $em, $event, $cache, $classLoader, $D2Config); return self::$em; }
/** * Setup Doctrine ORM */ protected function setupDoctrine() { //setup doctrine $doctrineConfig = new \Doctrine\ORM\Configuration(); //We use different caching and proxy settings in Development status if ($this->_config->getStatus() == 'DEVELOPMENT') { $doctrineConfig->setAutoGenerateProxyClasses(true); $doctrineConfig->setProxyDir($this->_config->getVarPath() . '/tmp'); } else { $doctrineConfig->setAutoGenerateProxyClasses(false); $doctrineConfig->setProxyDir(__DIR__ . '/Entity/Proxy'); if (!extension_loaded('apc')) { throw new Exception('APC cache is required, but was not available.'); } } $driver = $doctrineConfig->newDefaultAnnotationDriver(array(__DIR__ . "/Entity")); $doctrineConfig->setMetadataDriverImpl($driver); $doctrineConfig->setProxyNamespace('Jazzee\\Entity\\Proxy'); $doctrineConfig->setMetadataCacheImpl(self::getCache()); $doctrineConfig->setQueryCacheImpl(self::getCache()); $doctrineConfig->setResultCacheImpl(self::getCache()); $connectionParams = array('dbname' => $this->_config->getDbName(), 'user' => $this->_config->getDbUser(), 'password' => $this->_config->getDbPassword(), 'host' => $this->_config->getDbHost(), 'port' => $this->_config->getDbPort(), 'driver' => $this->_config->getDbDriver()); $previewStore = $this->_session->getStore('preview', 3600); if ($previewStore->check('previewdbpath')) { $this->_previewMode = true; $connectionParams['driver'] = 'pdo_sqlite'; $connectionParams['path'] = $previewStore->get('previewdbpath'); $exitLink = $this->path('preview/end'); $this->addMessage('info', "You are in preview mode, the changes you make will not be saved. You can exit preview mode by visiting <a href='{$exitLink}'>{$exitLink}</a>"); } $eventManager = new \Doctrine\Common\EventManager(); $eventManager->addEventListener(array(\Doctrine\ORM\Events::onFlush), new \Jazzee\Entity\ApplicantEventListener()); $eventManager->addEventListener(array(\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::preRemove), new \Jazzee\Entity\AnswerEventListener()); $eventManager->addEventListener(array(\Doctrine\ORM\Events::onFlush), new \Jazzee\Entity\ApplicationEventListener()); $this->_em = \Doctrine\ORM\EntityManager::create($connectionParams, $doctrineConfig, $eventManager); $this->_em->getConfiguration()->addCustomHydrationMode('ApplicantArrayHydrator', 'Jazzee\\Entity\\ApplicantArrayHydrator'); $this->_em->getConfiguration()->addCustomHydrationMode('ApplicantDisplayHydrator', 'Jazzee\\Entity\\ApplicantDisplayHydrator'); $this->_em->getConfiguration()->addCustomHydrationMode('ApplicantPDFTemplateHydrator', 'Jazzee\\Entity\\ApplicantPDFTemplateHydrator'); \Jazzee\Globals::setEntityManager($this->_em); }
/** * Returns the doctrine entity manager * @return \Doctrine\ORM\EntityManager */ public function getEntityManager() { if ($this->em) { return $this->em; } $config = new \Doctrine\ORM\Configuration(); //$config->setResultCacheImpl($this->cacheDriver); $config->setMetadataCacheImpl($this->cacheDriver); $config->setQueryCacheImpl($this->cacheDriver); $config->setProxyDir(ASCMS_MODEL_PROXIES_PATH); $config->setProxyNamespace('Cx\\Model\\Proxies'); /** * This should be set to true if workbench is present and active. * Just checking for workbench.config is not really a good solution. * Since ConfigurationFactory used by EM caches auto generation * config value, there's no possibility to set this later. */ $config->setAutoGenerateProxyClasses(file_exists(ASCMS_DOCUMENT_ROOT . '/workbench.config')); $connectionOptions = array('pdo' => $this->getPdoConnection(), 'dbname' => $this->db->getName()); $evm = new \Doctrine\Common\EventManager(); $chainDriverImpl = new \Doctrine\ORM\Mapping\Driver\DriverChain(); $driverImpl = new \Cx\Core\Model\Controller\YamlDriver(array(ASCMS_CORE_PATH . '/Core' . '/Model/Yaml')); $chainDriverImpl->addDriver($driverImpl, 'Cx'); //loggable stuff $loggableDriverImpl = $config->newDefaultAnnotationDriver(ASCMS_LIBRARY_PATH . '/doctrine/Gedmo/Loggable/Entity'); $chainDriverImpl->addDriver($loggableDriverImpl, 'Gedmo\\Loggable'); $this->loggableListener = new \Cx\Core\Model\Model\Event\LoggableListener(); $this->loggableListener->setUsername('currently_loggedin_user'); // in real world app the username should be loaded from session, example: // Session::getInstance()->read('user')->getUsername(); $evm->addEventSubscriber($this->loggableListener); $cx = \Cx\Core\Core\Controller\Cx::instanciate(); $sluggableDriverImpl = $config->newDefaultAnnotationDriver($cx->getCodeBaseLibraryPath() . '/doctrine/Gedmo/Sluggable'); $chainDriverImpl->addDriver($sluggableDriverImpl, 'Gedmo\\Sluggable'); $sluggableListener = new \Gedmo\Sluggable\SluggableListener(); // you should set the used annotation reader to listener, // to avoid creating new one for mapping drivers //$sluggableListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($sluggableListener); $timestampableDriverImpl = $config->newDefaultAnnotationDriver($cx->getCodeBaseLibraryPath() . '/doctrine/Gedmo/Timestampable'); $chainDriverImpl->addDriver($timestampableDriverImpl, 'Gedmo\\Timestampable'); $timestampableListener = new \Gedmo\Timestampable\TimestampableListener(); //$timestampableListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($timestampableListener); // Note that LANG_ID and other language constants/variables // have not been set yet! // $langCode = \FWLanguage::getLanguageCodeById(LANG_ID); // \DBG::log("LANG_ID ".LANG_ID.", language code: $langCode"); // -> LOG: LANG_ID LANG_ID, language code: $translatableDriverImpl = $config->newDefaultAnnotationDriver($cx->getCodeBaseLibraryPath() . '/doctrine/Gedmo/Translatable/Entity'); $chainDriverImpl->addDriver($translatableDriverImpl, 'Gedmo\\Translatable'); // RK: Note: // This might have been renamed in newer versions: //$translationListener = new \Gedmo\Translatable\TranslatableListener(); // In this Doctrine version, it is present as: $this->translationListener = new \Gedmo\Translatable\TranslationListener(); // current translation locale should be set from session // or hook later into the listener, // but *before the entity manager is flushed* // TODO: Set default locale from the default language? //$this->translationListener->setDefaultLocale('de_ch'); // Set the current locale (e.g. from the active language) // wherever that's required. //$translationListener->setTranslatableLocale('de_ch'); //$translationListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($this->translationListener); // RK: Note: // This is apparently not yet present in this Doctrine version: //$sortableListener = new \Gedmo\Sortable\SortableListener(); //$sortableListener->setAnnotationReader($cachedAnnotationReader); //$evm->addEventSubscriber($sortableListener); //tree stuff $treeListener = new \Gedmo\Tree\TreeListener(); $evm->addEventSubscriber($treeListener); $config->setMetadataDriverImpl($chainDriverImpl); //table prefix $prefixListener = new \DoctrineExtension\TablePrefixListener($this->db->getTablePrefix()); $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $prefixListener); $config->setSqlLogger(new \Cx\Lib\DBG\DoctrineSQLLogger()); $em = \Cx\Core\Model\Controller\EntityManager::create($connectionOptions, $config, $evm); //resolve enum, set errors $conn = $em->getConnection(); $conn->setCharset($this->db->getCharset()); $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); $conn->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string'); $this->em = $em; return $this->em; }
/** * Add configured event subscribers and listeners to the event manager * * @return \Doctrine\Common\EventManager * @throws \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException */ protected function buildEventManager() { $eventManager = new \Doctrine\Common\EventManager(); if (isset($this->settings['doctrine']['eventSubscribers']) && is_array($this->settings['doctrine']['eventSubscribers'])) { foreach ($this->settings['doctrine']['eventSubscribers'] as $subscriberClassName) { $subscriber = $this->objectManager->get($subscriberClassName); if (!$subscriber instanceof \Doctrine\Common\EventSubscriber) { throw new IllegalObjectTypeException('Doctrine eventSubscribers must extend class \\Doctrine\\Common\\EventSubscriber, ' . $subscriberClassName . ' fails to do so.', 1366018193); } $eventManager->addEventSubscriber($subscriber); } } if (isset($this->settings['doctrine']['eventListeners']) && is_array($this->settings['doctrine']['eventListeners'])) { foreach ($this->settings['doctrine']['eventListeners'] as $listenerOptions) { $listener = $this->objectManager->get($listenerOptions['listener']); $eventManager->addEventListener($listenerOptions['events'], $listener); } } return $eventManager; }
* * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ use Doctrine\Common\Annotations\AnnotationRegistry; // Check if configuration is present, otherwise include it if (!isset($orchestraConfig)) { include_once __DIR__ . '/../config.php'; } // Create an annotation configuration, using the configured environment // Tell Doctrine how to autoload the Assert annotations AnnotationRegistry::registerAutoloadNamespace("Symfony\\Component\\Validator\\Constraint", $orchestraConfig['vendorDir'] . '/symfony/validator'); // If multisite is set to true, we need to reload the cache even in production $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($entityPaths, $orchestraConfig['multisite'] ? true : $orchestraConfig['env'] == 'dev', $proxyDir, null, false); $config->setAutoGenerateProxyClasses(true); // Table Prefix $evm = new \Doctrine\Common\EventManager(); global $wpdb; $tablePrefix = new \Orchestra\DoctrineExtensions\TablePrefix($wpdb->prefix); $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); // Create an entity manager using the configured DB params and the configuration created above $em = \Doctrine\ORM\EntityManager::create($orchestraConfig['database'], $config, $evm); $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
/** * Returns the doctrine entity manager * @return \Doctrine\ORM\EntityManager */ public function getEntityManager() { if ($this->em) { return $this->em; } global $objCache; $config = new \Doctrine\ORM\Configuration(); $userCacheEngine = $objCache->getUserCacheEngine(); if (!$objCache->getUserCacheActive()) { $userCacheEngine = \Cx\Core_Modules\Cache\Controller\Cache::CACHE_ENGINE_OFF; } $arrayCache = new \Doctrine\Common\Cache\ArrayCache(); switch ($userCacheEngine) { case \Cx\Core_Modules\Cache\Controller\Cache::CACHE_ENGINE_APC: $cache = new \Doctrine\Common\Cache\ApcCache(); $cache->setNamespace($this->db->getName() . '.' . $this->db->getTablePrefix()); break; case \Cx\Core_Modules\Cache\Controller\Cache::CACHE_ENGINE_MEMCACHE: $memcache = $objCache->getMemcache(); if ($memcache instanceof \Memcache) { $cache = new \Doctrine\Common\Cache\MemcacheCache(); $cache->setMemcache($memcache); } elseif ($memcache instanceof \Memcached) { $cache = new \Doctrine\Common\Cache\MemcachedCache(); $cache->setMemcache($memcache); } $cache->setNamespace($this->db->getName() . '.' . $this->db->getTablePrefix()); break; case \Cx\Core_Modules\Cache\Controller\Cache::CACHE_ENGINE_XCACHE: $cache = new \Doctrine\Common\Cache\XcacheCache(); $cache->setNamespace($this->db->getName() . '.' . $this->db->getTablePrefix()); break; case \Cx\Core_Modules\Cache\Controller\Cache::CACHE_ENGINE_FILESYSTEM: $cache = new \Cx\Core_Modules\Cache\Controller\Doctrine\CacheDriver\FileSystemCache(ASCMS_CACHE_PATH); break; default: $cache = $arrayCache; break; } \Env::set('cache', $cache); //$config->setResultCacheImpl($cache); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); $config->setProxyDir(ASCMS_MODEL_PROXIES_PATH); $config->setProxyNamespace('Cx\\Model\\Proxies'); /** * This should be set to true if workbench is present and active. * Just checking for workbench.config is not really a good solution. * Since ConfigurationFactory used by EM caches auto generation * config value, there's no possibility to set this later. */ $config->setAutoGenerateProxyClasses(file_exists(ASCMS_DOCUMENT_ROOT . '/workbench.config')); $connectionOptions = array('pdo' => $this->getPdoConnection(), 'dbname' => $this->db->getName()); $evm = new \Doctrine\Common\EventManager(); $chainDriverImpl = new \Doctrine\ORM\Mapping\Driver\DriverChain(); $driverImpl = new \Cx\Core\Model\Controller\YamlDriver(array(ASCMS_CORE_PATH . '/Core' . '/Model/Yaml')); $chainDriverImpl->addDriver($driverImpl, 'Cx'); //loggable stuff $loggableDriverImpl = $config->newDefaultAnnotationDriver(ASCMS_LIBRARY_PATH . '/doctrine/Gedmo/Loggable/Entity'); $chainDriverImpl->addDriver($loggableDriverImpl, 'Gedmo\\Loggable'); $this->loggableListener = new \Cx\Core\Model\Model\Event\LoggableListener(); $this->loggableListener->setUsername('currently_loggedin_user'); // in real world app the username should be loaded from session, example: // Session::getInstance()->read('user')->getUsername(); $evm->addEventSubscriber($this->loggableListener); //tree stuff $treeListener = new \Gedmo\Tree\TreeListener(); $evm->addEventSubscriber($treeListener); $config->setMetadataDriverImpl($chainDriverImpl); //table prefix $prefixListener = new \DoctrineExtension\TablePrefixListener($this->db->getTablePrefix()); $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $prefixListener); $config->setSqlLogger(new \Cx\Lib\DBG\DoctrineSQLLogger()); $em = \Cx\Core\Model\Controller\EntityManager::create($connectionOptions, $config, $evm); //resolve enum, set errors $conn = $em->getConnection(); $conn->setCharset($this->db->getCharset()); $conn->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); $conn->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string'); $this->em = $em; return $this->em; }
<?php $lib = 'path/to/doctrine2/'; require $lib . 'lib/Doctrine/ORM/Tools/Setup.php'; Setup::registerAutoloadGit($lib); $cache = new \Doctrine\Common\Cache\ArrayCache(); $config = Setup::createAnnotationMetadataConfiguration(array(), true); $config->setSQLLogger(new Doctrine\DBAL\Logging\EchoSQLLogger()); $connectionOptions = array('driver' => 'pdo_sqlite', 'memory' => true); $evm = new \Doctrine\Common\EventManager(); $evm->addEventListener(array('postLoad'), new ActiveEntityListener()); $em = EntityManager::create($connectionOptions, $config, $evm); ActiveEntityRegistry::setDefaultManager($em); $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($em); $schemaTool->createSchema(array($em->getClassMetadata("Article"))); $article = new Article(); $article->setHeadline("foo"); $article->setBody("barz!"); $other = Article::create(array('headline' => 'foo', 'body' => 'omg!?')); $article->persist(); $other->persist(); $em->flush(); $em->clear(); $article = Article::find(1); $article->remove(); $em->flush(); $articles = Article::findBy(array('headline' => 'foo')); echo count($articles) . " articles\n"; $articles = Article::createQueryBuilder('r')->where(Article::expr()->like("r.body", '%omg%')); echo count($articles) . " articles\n";
/** * Initialize auto loader of Doctrine * * @return Doctrine_Enitity_Manager */ public static function init($clansuite_config) { self::checkDataSourceName($clansuite_config); // ensure doctrine2 exists in the libraries folder if (is_file(ROOT_LIBRARIES . 'Doctrine/Common/ClassLoader.php') === false) { throw new Koch_Exception('Doctrine2 not found. Check Libraries Folder.', 100); } // get isolated loader require ROOT_LIBRARIES . 'Doctrine/Common/ClassLoader.php'; // setup autoloaders with namespace and path to search in $classLoader = new \Doctrine\Common\ClassLoader('Doctrine', realpath(ROOT_LIBRARIES)); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Symfony', realpath(ROOT_LIBRARIES . 'Doctrine/Symfony')); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Entities', realpath(ROOT . 'doctrine')); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Repositories', realpath(ROOT . 'doctrine')); $classLoader->register(); $classLoader = new \Doctrine\Common\ClassLoader('Proxies', realpath(ROOT . 'doctrine')); $classLoader->register(); // include Doctrine Extensions $classLoader = new \Doctrine\Common\ClassLoader('DoctrineExtensions', realpath(ROOT_LIBRARIES)); $classLoader->register(); // fetch doctrine config handler for configuring $config = new \Doctrine\ORM\Configuration(); // fetch cache driver - APC in production and Array in development mode if (extension_loaded('apc') and DEBUG == false) { $cache = new \Doctrine\Common\Cache\ApcCache(); } else { $cache = new \Doctrine\Common\Cache\ArrayCache(); } // set cache driver $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); // set annotation driver for entities $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(self::getModelPathsForAllModules())); // @todo workaround till i find a better way to acquire all the models $config->getMetadataDriverImpl()->getAllClassNames(); #Koch_Debug::firebug($config->getMetadataDriverImpl()->getAllClassNames()); // set proxy dirs $config->setProxyDir(realpath(ROOT . 'doctrine')); $config->setProxyNamespace('Proxies'); // regenerate proxies only in debug and not in production mode if (DEBUG == true) { $config->setAutoGenerateProxyClasses(true); } else { $config->setAutoGenerateProxyClasses(false); } // use main configuration values for setting up the connection $connectionOptions = array('driver' => $clansuite_config['database']['driver'], 'user' => $clansuite_config['database']['user'], 'password' => $clansuite_config['database']['password'], 'dbname' => $clansuite_config['database']['dbname'], 'host' => $clansuite_config['database']['host'], 'charset' => $clansuite_config['database']['charset'], 'driverOptions' => array('charset' => $clansuite_config['database']['charset'])); // set up Logger #$config->setSqlLogger(new \Doctrine\DBAL\Logging\EchoSqlLogger); // we need some more functions for mysql $config->addCustomNumericFunction('RAND', 'DoctrineExtensions\\Query\\Mysql\\Rand'); /** * Events */ $event = new \Doctrine\Common\EventManager(); /** * Database Prefix * * The constant definition is for building (raw) sql queries manually. * The database prefixing is registered via an event. */ define('DB_PREFIX', $clansuite_config['database']['prefix']); $tablePrefix = new \DoctrineExtensions\TablePrefix\TablePrefix(DB_PREFIX); $event->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); /** * Custom Functions * * We need some more functions for mysql, like RAND for random values. */ $config->addCustomNumericFunction('RAND', 'DoctrineExtensions\\Query\\Mysql\\Rand'); /** * Set UTF-8 handling of database data via Doctrine Event for MySQL. */ if ($clansuite_config['database']['driver'] !== null and $clansuite_config['database']['driver'] == "pdo_mysql") { /** * @todo eval database.charset true? * wouldn't it be better to use utf-8 to name it explicitly */ if ($clansuite_config['database']['charset'] !== null) { $event->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit($clansuite_config['database']['charset'], 'utf8_unicode_ci')); } } // Entity manager $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config, $event); // set DBAL DebugStack Logger (also needed for counting queries) if (defined('DEBUG') and DEBUG == 1) { self::$sqlLoggerStack = new \Doctrine\DBAL\Logging\DebugStack(); $em->getConfiguration()->setSQLLogger(self::$sqlLoggerStack); /** * Echo SQL Queries directly on the page. */ #$em->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger()); } self::$em = $em; // done with config, remove to safe memory unset($clansuite_config, $em, $event); return self::$em; }