/** * @return EntityManager */ protected function getEntityManager() { if (null !== $this->em) { return $this->em; } $config = new Configuration(); $config->setMetadataCacheImpl(new ArrayCache()); $config->setQueryCacheImpl(new ArrayCache()); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setAutoGenerateProxyClasses(ProxyFactory::AUTOGENERATE_EVAL); $config->setProxyNamespace('SimpleThings\\EntityAudit\\Tests\\Proxies'); $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(array(realpath(__DIR__ . '/Fixtures/Core'), realpath(__DIR__ . '/Fixtures/Issue'), realpath(__DIR__ . '/Fixtures/Relation')), false)); Gedmo\DoctrineExtensions::registerAnnotations(); $connection = $this->_getConnection(); // get rid of more global state $evm = $connection->getEventManager(); foreach ($evm->getListeners() as $event => $listeners) { foreach ($listeners as $listener) { $evm->removeEventListener(array($event), $listener); } } $this->em = EntityManager::create($connection, $config); if (isset($this->customTypes) and is_array($this->customTypes)) { foreach ($this->customTypes as $customTypeName => $customTypeClass) { if (!Type::hasType($customTypeName)) { Type::addType($customTypeName, $customTypeClass); } $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('db_' . $customTypeName, $customTypeName); } } return $this->em; }
/** * Get entity manager. * * @return EntityManagerInterface */ protected function getEntityManager() { if (null === $this->entityManager) { $params = ['driver' => 'pdo_sqlite', 'memory' => true]; $cache = new ArrayCache(); /** @var AnnotationReader $reader */ $reader = new CachedReader(new AnnotationReader(), $cache); $annotationDriver = new AnnotationDriver($reader, [__DIR__ . '/../../../src/ORM']); $driverChain = new MappingDriverChain(); $driverChain->addDriver($annotationDriver, Commander::ENTITY_NAMESPACE); DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $reader); $config = new Configuration(); $config->setAutoGenerateProxyClasses(true); $config->setProxyDir(sys_get_temp_dir()); $config->setProxyNamespace(Commander::ENTITY_NAMESPACE); $config->setMetadataDriverImpl($driverChain); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); $config->setResultCacheImpl($cache); $config->setHydrationCacheImpl($cache); $timestampableListener = new TimestampableListener(); $timestampableListener->setAnnotationReader($annotationDriver->getReader()); $eventManager = new EventManager(); $eventManager->addEventSubscriber($timestampableListener); $entityManager = EntityManager::create($params, $config, $eventManager); $schemaTool = new SchemaTool($entityManager); $schemaTool->createSchema($entityManager->getMetadataFactory()->getAllMetadata()); $this->entityManager = $entityManager; } return $this->entityManager; }
/** * Registers services on the given app. * * This method should only be used to configure services and parameters. * It should not get services. * @param Application $app */ public function register(Application $app) { parent::register($app); $app->register(new \Silex\Provider\DoctrineServiceProvider(), ['db.options' => $app['config']['db.options']]); $app->register(new DoctrineOrmServiceProvider(), $app['config']['orm.options']); if (getenv('MIGRATION_COMMANDS')) { $app->register(new MigrationServiceProvider(), ['db.migrations.path' => $app['config']['migrations.directory']]); } $app['orm.em'] = $app->extend('orm.em', function (EntityManagerInterface $em) use($app) { if (file_exists(APP_PATH . '/vendor/apitude/apitude/src/Annotations/APIAnnotations.php')) { AnnotationRegistry::registerFile(APP_PATH . '/vendor/apitude/apitude/src/Annotations/APIAnnotations.php'); } /** @var Configuration $config */ $config = $em->getConfiguration(); $config->setMetadataCacheImpl($app['cache']); $config->addCustomHydrationMode('simple', SimpleHydrator::class); /** @var MappingDriverChain $driver */ $driver = $config->getMetadataDriverImpl(); // gedmo initialization $reader = new AnnotationReader(); $cache = new CachedReader($reader, $app['cache']); DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driver, $cache); return $em; }); }
public function register(Application $app) { $app['orm.em.paths'] = $app->share(function () { return array(); }); $app['orm.event_manager'] = $app->share(function () use($app) { return new EventManager(); }); $app['orm.config'] = $app->share(function () use($app) { return Setup::createConfiguration($app['debug']); }); $app['orm.anotation_reader'] = $app->share(function () use($app) { $annotationReader = new AnnotationReader(); $cache = $app['orm.config']->getMetadataCacheImpl(); return new CachedReader($annotationReader, $cache); }); $app['orm.default_anotation_driver'] = $app->share(function () use($app) { AnnotationRegistry::registerFile($app['vendor_dir'] . '/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); return new AnnotationDriver($app['orm.anotation_reader'], $app['orm.em.paths']); }); $app['orm.em'] = $app->share(function () use($app) { $annotationReader = $app['orm.anotation_reader']; $eventManager = $app['orm.event_manager']; $driverChain = new MappingDriverChain(); $driverChain->setDefaultDriver($app['orm.default_anotation_driver']); DoctrineExtensions::registerMappingIntoDriverChainORM($driverChain, $annotationReader); $loggableListener = new LoggableListener(); $loggableListener->setAnnotationReader($annotationReader); $loggableListener->setUsername('admin'); $eventManager->addEventSubscriber($loggableListener); $config = $app['orm.config']; $config->setMetadataDriverImpl($driverChain); return EntityManager::create($app['db.default_options'], $config, $eventManager); }); }
/** * * @param array $config * @return DocumentManager */ public static function createDocumentManager($config, Container $container) { $configuration = new Configuration(); if (is_null($config['eventManager'])) { $evm = new EventManager(); } else { $evm = $config['eventManager']; } $configuration->setProxyDir($config['proxyDir']); $configuration->setProxyNamespace($config['proxyNamespace']); $configuration->setHydratorDir($config['hydratorDir']); $configuration->setHydratorNamespace($config['hydratorNamespace']); $configuration->setAutoGenerateHydratorClasses($config['autoGenerateHydratorClasses']); $configuration->setAutoGenerateProxyClasses($config['autoGenerateProxyClasses']); if (isset($config['metaDataCache'])) { $metadataCache = $config['metaDataCache']; } else { $metadataCache = new $config['metaDataCacheClass'](); $metadataCache->setNamespace($config['cachePrefix']); } $configuration->setMetadataCacheImpl($metadataCache); AnnotationDriver::registerAnnotationClasses(); $reader = new AnnotationReader(); if ($config['cacheAnnotations'] == TRUE) { $reader = new CachedReader($reader, $metadataCache, $config['debug']); } if ($config['indexAnnotations'] == TRUE) { $reader = new IndexedReader($reader); } if (class_exists(\Gedmo\DoctrineExtensions::class)) { \Gedmo\DoctrineExtensions::registerAnnotations(); $configuration->addFilter('soft-deleteable', \Gedmo\SoftDeleteable\Filter\ODM\SoftDeleteableFilter::class); foreach ($config['listeners'] as $listenerName => $enabled) { if ($enabled) { $listener = self::configureListener($listenerName, $reader); $evm->addEventSubscriber($listener); } } } $driverImpl = new AnnotationDriver($reader, $config['documentsDir']); $configuration->setMetadataDriverImpl($driverImpl); $configuration->setDefaultDB($config['dbname']); $logger = new Logger($config['logger'], $config['loggerPrefix']); $configuration->setLoggerCallable([$logger, 'logQuery']); $mongo = new MongoClient($config['uri'], $config['mongoOptions']); $connection = new Connection($mongo); $dm = DocumentManager::create($connection, $configuration, $evm); foreach ($config['filters'] as $filter => $enabled) { if ($enabled) { $dm->getFilterCollection()->enable($filter); } } return $dm; }
/** * Boot the service provider * * @param ManagerRegistry $registry */ public function boot(ManagerRegistry $registry) { foreach ($registry->getManagers() as $manager) { $chain = $manager->getConfiguration()->getMetadataDriverImpl(); $reader = $chain->getReader(); if ($this->app->make('config')->get('doctrine.gedmo.all_mappings', false)) { DoctrineExtensions::registerMappingIntoDriverChainORM($chain, $reader); } else { DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($chain, $reader); } } }
/** * Get mapping driver. * * @return MappingDriver */ public function getMappingDriver() { if (null === $this->mappingDriver) { /** @var AnnotationReader $reader */ $reader = new CachedReader(new AnnotationReader(), $this->cache); $annotationDriver = new AnnotationDriver($reader, [__DIR__ . '/../ORM']); $driverChain = new MappingDriverChain(); $driverChain->addDriver($annotationDriver, Commander::ENTITY_NAMESPACE); DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $reader); $this->mappingDriver = $driverChain; } return $this->mappingDriver; }
/** * @param ContainerInterface $container * * @return EntityManagerInterface * @throws ORMException */ public function __invoke(ContainerInterface $container) { $config = $container->has('config') ? $container->get('config') : []; $proxyDir = isset($config['doctrine']['orm']['proxy_dir']) ? $config['doctrine']['orm']['proxy_dir'] : 'data/cache/EntityProxy'; $proxyNamespace = isset($config['doctrine']['orm']['proxy_namespace']) ? $config['doctrine']['orm']['proxy_namespace'] : 'EntityProxy'; $autoGenerateProxyClasses = isset($config['doctrine']['orm']['auto_generate_proxy_classes']) ? $config['doctrine']['orm']['auto_generate_proxy_classes'] : false; $underscoreNamingStrategy = isset($config['doctrine']['orm']['underscore_naming_strategy']) ? $config['doctrine']['orm']['underscore_naming_strategy'] : false; $entityPaths = isset($config['doctrine']['orm']['entity_paths']) ? $config['doctrine']['orm']['entity_paths'] : ['src']; // Doctrine ORM $doctrine = new Configuration(); $doctrine->setProxyDir($proxyDir); $doctrine->setProxyNamespace($proxyNamespace); $doctrine->setAutoGenerateProxyClasses($autoGenerateProxyClasses); if ($underscoreNamingStrategy) { $doctrine->setNamingStrategy(new UnderscoreNamingStrategy()); } // Cache $cache = $container->get(Cache::class); $doctrine->setQueryCacheImpl($cache); $doctrine->setResultCacheImpl($cache); $doctrine->setMetadataCacheImpl($cache); // ORM mapping by Annotation AnnotationRegistry::registerFile('vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); if (class_exists(DoctrineExtensions::class)) { DoctrineExtensions::registerAnnotations(); } $cachedAnnotationReader = new CachedReader(new AnnotationReader(), $cache); $driver = new AnnotationDriver($cachedAnnotationReader, $entityPaths); $doctrine->setMetadataDriverImpl($driver); $eventManager = new EventManager(); if (isset($config['doctrine']['orm']['event_subscribers'])) { foreach ($config['doctrine']['orm']['event_subscribers'] as $subscriber) { $subscriberInstance = $container->get($subscriber); if ($subscriberInstance instanceof MappedEventSubscriber) { $subscriberInstance->setAnnotationReader($cachedAnnotationReader); } $eventManager->addEventSubscriber($subscriberInstance); } } $entityManager = EntityManager::create($config['doctrine']['connection']['orm_default'], $doctrine, $eventManager); // Types Type::addType('uuid', UuidType::class); $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('uuid', 'uuid'); if (isset($config['doctrine']['orm']['types'])) { foreach ($config['doctrine']['orm']['types'] as $type => $class) { Type::addType($type, $class); } } return $entityManager; }
/** * @param $datasourceName * @return mixed */ public function getEntityManager($datasourceName = null) { if ($datasourceName === null) { $datasourceName = ConfigManager::get('datasources.default'); } else { if (!is_string($datasourceName) || empty($datasourceName)) { throw new \InvalidArgumentException('Invalid datasource name "' . (string) $datasourceName . '"'); } } if (!array_key_exists($datasourceName, self::$connections)) { $isDebug = ConfigManager::exists('datasources.debug') ? ConfigManager::get('datasources.debug') : false; $cacheName = ConfigManager::get('datasources.list.' . $datasourceName . '.cache'); $cacheClass = '\\Doctrine\\Common\\Cache\\' . (!empty($cacheName) ? $cacheName : 'ArrayCache'); $entityManagerConfig = Setup::createConfiguration($isDebug); //Load annotations stuff AnnotationRegistry::registerFile(VENDORS_DIR . 'doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); $cache = new $cacheClass(); $annotationReader = new AnnotationReader(); $cachedAnnotationReader = new CachedReader($annotationReader, $cache, $isDebug); //Load event manager $this->eventManager = new EventManager(); $listenersList = ConfigManager::get('datasources.listeners'); if (!empty($listenersList)) { foreach ($listenersList as $listener) { $l = new $listener(); $this->eventManager->addEventSubscriber($l); } } //Tables prefix if (ConfigManager::exists('datasources.list.' . $datasourceName . '.prefix')) { $tablePrefix = new DoctrineTablePrefixListener(ConfigManager::get('datasources.list.' . $datasourceName . '.prefix')); $this->eventManager->addEventListener(Events::loadClassMetadata, $tablePrefix); } //Load doctrine extensions listeners if any if (!empty($listenersList) && class_exists('\\Gedmo\\DoctrineExtensions')) { $driverChain = new MappingDriverChain(); DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $cachedAnnotationReader); } $driver = new AnnotationDriver($cachedAnnotationReader, glob(APP_DIR . '*/entity')); $entityManagerConfig->setMetadataDriverImpl($driver); self::$entityManagers[$datasourceName] = EntityManager::create(ConfigManager::get('datasources.list.' . $datasourceName), $entityManagerConfig, $this->eventManager); } return self::$entityManagers[$datasourceName]; }
/** * {@inheritdoc} */ public function register(Application $app) { $doctrine = (require CONFIG_PATH . DIRECTORY_SEPARATOR . 'doctrine.php'); $mappings = $doctrine['orm']['orm.em.options']['mappings']; $paths = []; foreach ($mappings as $mapping) { $paths[] = $mapping['path']; } $reader = new CachedReader(new AnnotationReader(), new ArrayCache()); $driverChain = new DriverChain(); DoctrineExtensions::registerMappingIntoDriverChainORM($driverChain, $reader); $annotationDriver = new AnnotationDriver($reader, $paths); foreach ($mappings as $mapping) { $driverChain->addDriver($annotationDriver, $mapping['namespace']); } if (!isset($app['orm.em'])) { throw new FatalErrorException('The DoctrineOrmServiceProvider is not registered in this application'); } $app['orm.em']->getConfiguration()->setMetadataDriverImpl($driverChain); }
/** * @inheritdoc */ public function start() { parent::start(); $connectionConfig = $this->config('connection'); if (!empty($connectionConfig) && is_array($connectionConfig)) { // Setup Doctrine. Largely borrowed from // https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/annotations.md#em-setup // Register Doctrine default annotations. AnnotationRegistry::registerFile($this->getEngine()->getSiteInfo()->getSiteRoot() . '/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); // Setup annotation metadata cache if ($this->getEngine()->getEnvironmentInfo()->isDevMode() || !$this->getEngine()->config('memcache.enabled')) { $cache = new ArrayCache(); } else { $cache = new MemcacheCache(); $cache->setMemcache($this->getEngine()->getMemcache()); } // Setup annotation metadata reader and driver /** @var AnnotationReader $cachedAnnotationReader (for all intents and purposes...) */ $cachedAnnotationReader = new CachedReader(new AnnotationReader(), $cache); $this->driverChain = new MappingDriverChain(); $this->annotationDriver = new AnnotationDriver($cachedAnnotationReader, array($this->getEngine()->getApplicationInfo()->getSitegearRoot())); // Setup Gedmo extension annotations \Gedmo\DoctrineExtensions::registerAnnotations(); $this->driverChain->addDriver($this->annotationDriver, 'Gedmo'); // Setup Sitegear extension annotations // TODO Make model-providing modules declare their own namespaces $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\Customer\\Model'); $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\News\\Model'); $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\Locations\\Model'); $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\Products\\Model'); // Create the entity manager configuration, with proxy generation, cached metadata and lowercase-underscore // database naming convention. $entityManagerConfig = new Configuration(); // TODO Make this a temp directory set in the engine config $entityManagerConfig->setProxyDir(sys_get_temp_dir()); // TODO Configurable namespace and naming strategy $entityManagerConfig->setProxyNamespace('Proxy'); $entityManagerConfig->setAutoGenerateProxyClasses($this->getEngine()->getEnvironmentInfo()->isDevMode()); $entityManagerConfig->setMetadataDriverImpl($this->driverChain); $entityManagerConfig->setMetadataCacheImpl($cache); $entityManagerConfig->setQueryCacheImpl($cache); $entityManagerConfig->setNamingStrategy(new UnderscoreNamingStrategy(CASE_LOWER)); // Setup event subscribers. $eventManager = new EventManager(); foreach ($this->config('orm.subscribers') as $subscriberConfig) { /** @var \Doctrine\Common\EventSubscriber $subscriber */ $subscriber = TypeUtilities::buildTypeCheckedObject($subscriberConfig['class'], 'event subscriber', null, array('\\Doctrine\\Common\\EventSubscriber'), isset($subscriberConfig['arguments']) ? $subscriberConfig['arguments'] : array()); if ($subscriber instanceof MappedEventSubscriber) { /** @var MappedEventSubscriber $subscriber */ $subscriber->setAnnotationReader($cachedAnnotationReader); } $eventManager->addEventSubscriber($subscriber); } // Create the entity manager using the configured connection parameters. $this->entityManager = EntityManager::create($this->config('connection'), $entityManagerConfig, $eventManager); // Register the JSON custom data type. This has to be done last, when the entity manager has a connection. foreach ($this->config('dbal.types') as $key => $className) { Type::addType($key, $className); $this->entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping(preg_replace('/^.*\\\\(.*?)$/', '$1', $className), $key); } } else { throw new \DomainException('<h1>Incorrect or Missing Configuration</h1><p>You have attempted to use the Doctrine module in your site, but you have not provided all the required connection parameters in your configuration file.</p><p>Please rectify this by providing connection parameters ("driver", "dbname", plus normally "username" and "password") or disabling the Doctrine module.</p>'); } }
/** * @return $this */ public function connect() { // Prevent to connect twice if ($this->entityManager) { return $this; } $applicationDir = $this->core->getApplicationDir(); $this->createModuleDirCache(); $cache = $this->cache->getCacheProvider(); $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl($cache); $config->addCustomStringFunction('MD5', '\\DoctrineExtensions\\Query\\Mysql\\Md5'); $config->addCustomStringFunction('ACOS', '\\DoctrineExtensions\\Query\\Mysql\\Acos'); $config->addCustomStringFunction('ASIN', '\\DoctrineExtensions\\Query\\Mysql\\Asin'); $config->addCustomStringFunction('ATAN', '\\DoctrineExtensions\\Query\\Mysql\\Atan'); $config->addCustomStringFunction('ATAN2', '\\DoctrineExtensions\\Query\\Mysql\\Atan2'); $config->addCustomStringFunction('BINARY', '\\DoctrineExtensions\\Query\\Mysql\\Binary'); $config->addCustomStringFunction('CHARLENGTH', '\\DoctrineExtensions\\Query\\Mysql\\CharLength'); $config->addCustomStringFunction('CONCATWS', '\\DoctrineExtensions\\Query\\Mysql\\ConcatWs'); $config->addCustomStringFunction('COS', '\\DoctrineExtensions\\Query\\Mysql\\Cos'); $config->addCustomStringFunction('COT', '\\DoctrineExtensions\\Query\\Mysql\\COT'); $config->addCustomStringFunction('COUNTIF', '\\DoctrineExtensions\\Query\\Mysql\\CountIf'); $config->addCustomStringFunction('CRC32', '\\DoctrineExtensions\\Query\\Mysql\\Crc32'); $config->addCustomStringFunction('DATE', '\\DoctrineExtensions\\Query\\Mysql\\Date'); $config->addCustomStringFunction('DATEADD', '\\DoctrineExtensions\\Query\\Mysql\\DateAdd'); $config->addCustomStringFunction('DATEDIFF', '\\DoctrineExtensions\\Query\\Mysql\\DateFormat'); $config->addCustomStringFunction('DAY', '\\DoctrineExtensions\\Query\\Mysql\\Day'); $config->addCustomStringFunction('DEGREES', '\\DoctrineExtensions\\Query\\Mysql\\Degrees'); $config->addCustomStringFunction('FIELD', '\\DoctrineExtensions\\Query\\Mysql\\Field'); $config->addCustomStringFunction('FINDINSET', '\\DoctrineExtensions\\Query\\Mysql\\FindInSet'); $config->addCustomStringFunction('GROUPCONCAT', '\\DoctrineExtensions\\Query\\Mysql\\GroupConcat'); $config->addCustomStringFunction('HOUR', '\\DoctrineExtensions\\Query\\Mysql\\Hour'); $config->addCustomStringFunction('IFELSE', '\\DoctrineExtensions\\Query\\Mysql\\IfElse'); $config->addCustomStringFunction('IFNULL', '\\DoctrineExtensions\\Query\\Mysql\\IfNUll'); $config->addCustomStringFunction('MATCHAGAINST', '\\DoctrineExtensions\\Query\\Mysql\\MatchAgainst'); $config->addCustomStringFunction('MONTH', '\\DoctrineExtensions\\Query\\Mysql\\Month'); $config->addCustomStringFunction('NULLIF', '\\DoctrineExtensions\\Query\\Mysql\\NullIf'); $config->addCustomStringFunction('PI', '\\DoctrineExtensions\\Query\\Mysql\\Pi'); $config->addCustomStringFunction('RADIANS', '\\DoctrineExtensions\\Query\\Mysql\\Radians'); $config->addCustomStringFunction('RAND', '\\DoctrineExtensions\\Query\\Mysql\\Rand'); $config->addCustomStringFunction('REGEXP', '\\DoctrineExtensions\\Query\\Mysql\\Regexp'); $config->addCustomStringFunction('ROUND', '\\DoctrineExtensions\\Query\\Mysql\\Round'); $config->addCustomStringFunction('SHA1', '\\DoctrineExtensions\\Query\\Mysql\\Sha1'); $config->addCustomStringFunction('SHA2', '\\DoctrineExtensions\\Query\\Mysql\\Sha2'); $config->addCustomStringFunction('SIN', '\\DoctrineExtensions\\Query\\Mysql\\Sin'); $config->addCustomStringFunction('STRTODATE', '\\DoctrineExtensions\\Query\\Mysql\\StrToDate'); $config->addCustomStringFunction('TAN', '\\DoctrineExtensions\\Query\\Mysql\\Tan'); $config->addCustomStringFunction('TIMESTAMPDIFF', '\\DoctrineExtensions\\Query\\Mysql\\TimestampDiff'); $config->addCustomStringFunction('WEEK', '\\DoctrineExtensions\\Query\\Mysql\\Week'); $config->addCustomStringFunction('YEAR', '\\DoctrineExtensions\\Query\\Mysql\\Year'); if (!defined('ENV') || ENV === \Fraym\Core::ENV_DEVELOPMENT) { $config->setAutoGenerateProxyClasses(true); } $modelDirs = $this->getModuleDirCache(); \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(function ($class) { return class_exists($class, true); }); $annotationReader = new \Doctrine\Common\Annotations\AnnotationReader(); $this->cachedAnnotationReader = new \Doctrine\Common\Annotations\CachedReader($annotationReader, $cache); $this->annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($this->cachedAnnotationReader, $modelDirs); /** * Ignore PHP-DI Annotation */ $annotationReader->addGlobalIgnoredName('Injectable'); $annotationReader->addGlobalIgnoredName('Inject'); $config->setMetadataDriverImpl($this->annotationDriver); $config->setQueryCacheImpl($cache); $config->setResultCacheImpl($cache); $config->setProxyDir($applicationDir . DIRECTORY_SEPARATOR . CACHE_DOCTRINE_PROXY_PATH); $config->setProxyNamespace('Proxies'); $this->fetchMode = \PDO::FETCH_OBJ; $tablePrefix = new TablePrefix(DB_TABLE_PREFIX); $this->eventManager = new \Doctrine\Common\EventManager(); $this->eventManager->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix); $this->entityManager = \Doctrine\ORM\EntityManager::create($this->connectionOptions, $config, $this->eventManager); $this->pdo = $this->entityManager->getConnection(); $this->pdo->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string'); $driverChain = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain(); \Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $this->cachedAnnotationReader); $this->eventManager->addEventListener([\Doctrine\ORM\Events::preRemove, \Doctrine\ORM\Events::postRemove, \Doctrine\ORM\Events::prePersist, \Doctrine\ORM\Events::postPersist, \Doctrine\ORM\Events::preUpdate, \Doctrine\ORM\Events::postUpdate, \Doctrine\ORM\Events::postLoad, \Doctrine\ORM\Events::onFlush], $this->eventListener); return $this; }
public function register(Application $app) { $app['EM.sql-logger.file'] = $app->share(function (Application $app) { return $app['log.path'] . '/doctrine-log.log'; }); $app['EM.sql-logger.max-files'] = 5; $app['EM.sql-logger'] = $app->share(function (Application $app) { $logger = new $app['monolog.logger.class']('doctrine-logger'); $logger->pushHandler(new RotatingFileHandler($app['EM.sql-logger.file'], $app['EM.sql-logger.max-files'])); return new MonologSQLLogger($logger, 'yaml'); }); $app['EM.driver'] = $app->share(function (Application $app) { AnnotationRegistry::registerFile($app['root.path'] . '/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); $annotationReader = new AnnotationReader(); $fileCacheReader = new FileCacheReader($annotationReader, $app['cache.path'] . '/doctrine', $app['debug']); $driverChain = new MappingDriverChain(); DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $fileCacheReader); $annotationDriver = new AnnotationDriver($annotationReader, [$app['root.path'] . '/lib/Alchemy/Phrasea/Model/Entities']); $driverChain->addDriver($annotationDriver, 'Alchemy\\Phrasea\\Model\\Entities'); return $driverChain; }); $app['EM.config'] = $app->share(function (Application $app) { $config = new ORMConfiguration(); if ($app->getEnvironment() === PhraseaApplication::ENV_DEV) { $config->setSQLLogger($app['EM.sql-logger']); } $config->setMetadataCacheImpl($app['phraseanet.cache-service']->factory('ORMmetadata', $app['EM.opcode-cache-type'], $app['EM.opcode-cache-options'])); $config->setQueryCacheImpl($app['phraseanet.cache-service']->factory('ORMquery', $app['EM.opcode-cache-type'], $app['EM.opcode-cache-options'])); $config->setResultCacheImpl($app['phraseanet.cache-service']->factory('ORMresult', $app['EM.cache-type'], $app['EM.cache-options'])); $config->setAutoGenerateProxyClasses($app['debug']); $config->setMetadataDriverImpl($app['EM.driver']); $config->setProxyDir($app['root.path'] . '/resources/proxies'); $config->setProxyNamespace('Alchemy\\Phrasea\\Model\\Proxies'); $config->setAutoGenerateProxyClasses($app['debug']); $config->addEntityNamespace('Phraseanet', 'Alchemy\\Phrasea\\Model\\Entities'); return $config; }); $app['EM.opcode-cache-type'] = $app->share(function (Application $app) { if ($app['configuration.store']->isSetup()) { return $app['conf']->get(['main', 'opcodecache', 'type']); } return 'ArrayCache'; }); $app['EM.opcode-cache-options'] = $app->share(function (Application $app) { if ($app['configuration.store']->isSetup()) { return $app['conf']->get(['main', 'opcodecache', 'options']); } return []; }); $app['EM.cache-type'] = $app->share(function (Application $app) { if ($app['configuration.store']->isSetup()) { return $app['conf']->get(['main', 'cache', 'type']); } return 'ArrayCache'; }); $app['EM.cache-options'] = $app->share(function (Application $app) { if ($app['configuration.store']->isSetup()) { return $app['conf']->get(['main', 'cache', 'options']); } return []; }); $app['EM.events-manager'] = $app->share(function (Application $app) { $evm = new EventManager(); $evm->addEventSubscriber(new TimestampableListener()); return $evm; }); $app['EM.dbal-conf'] = $app->share(function (Application $app) { if ('test' === $app->getEnvironment()) { return $app['conf']->get(['main', 'database-test']); } return $app['conf']->get(['main', 'database']); }); $app['dbal.provider'] = $app->share(function (Application $app) { return new ConnectionProvider($app['EM.config'], $app['EM.events-manager'], isset($app['task-manager.logger']) ? $app['task-manager.logger'] : $app['monolog']); }); $app['EM'] = $app->share(function (Application $app) { try { $em = EntityManager::create($app['EM.dbal-conf'], $app['EM.config'], $app['EM.events-manager']); } catch (\Exception $e) { throw new RuntimeException("Unable to create database connection", $e->getCode(), $e); } $platform = $em->getConnection()->getDatabasePlatform(); $types = ['blob' => 'Alchemy\\Phrasea\\Model\\Types\\Blob', 'enum' => 'Alchemy\\Phrasea\\Model\\Types\\Blob', 'longblob' => 'Alchemy\\Phrasea\\Model\\Types\\LongBlob', 'varbinary' => 'Alchemy\\Phrasea\\Model\\Types\\VarBinary', 'binary' => 'Alchemy\\Phrasea\\Model\\Types\\Binary', 'binary_string' => 'Alchemy\\Phrasea\\Model\\Types\\BinaryString']; foreach ($types as $type => $class) { if (!Type::hasType($type)) { Type::addType($type, $class); } $platform->registerDoctrineTypeMapping($type, $type); } return $em; }); $app['EM.native-query'] = $app->share(function ($app) { return new NativeQueryProvider($app['EM']); }); }
protected function createDriver() { $this->driverChain = new \Doctrine\ORM\Mapping\Driver\DriverChain(); \Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($this->driverChain, $this->cachedAnnotationReader); $entityDir = $this->config['general.namespace'] . '/Model/Entity'; $entityPath = $this->config['general.appDir'] . 'src/' . $entityDir; $this->annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($this->cachedAnnotationReader, array($entityPath)); $this->driverChain->addDriver($this->annotationDriver, $this->config['general.namespace'] . '\\Model\\Entity'); $this->doctrineConfig->setMetadataDriverImpl($this->driverChain); }
/** * Todo: Should be removed once GedmoExtension in the laravel-doctrine/extensions repo is tested to work * @param bool $all */ public function enableGedmoExtensions($all = true) { if ($all) { DoctrineExtensions::registerMappingIntoDriverChainORM($this->driverChain->getChain(), $this->driverChain->getReader()); } else { DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($this->driverChain->getChain(), $this->driverChain->getReader()); } }
private function setupOrms() { $app = $this; // Override "orm.cache.configurer" service provided for benefiting // of "phraseanet.cache-service" $app['orm.cache.configurer'] = $app->protect(function ($name, Configuration $config, $options) use($app) { /** @var Manager $service */ $service = $app['phraseanet.cache-service']; $config->setMetadataCacheImpl($service->factory('ORM_metadata', $app['orm.cache.driver'], $app['orm.cache.options'])); $config->setQueryCacheImpl($service->factory('ORM_query', $app['orm.cache.driver'], $app['orm.cache.options'])); $config->setResultCacheImpl($service->factory('ORM_result', $app['orm.cache.driver'], $app['orm.cache.options'])); $config->setHydrationCacheImpl($service->factory('ORM_hydration', $app['orm.cache.driver'], $app['orm.cache.options'])); }); $app['orm.proxies_dir'] = $app['root.path'] . '/resources/proxies'; $app['orm.auto_generate_proxies'] = $app['debug']; $app['orm.proxies_namespace'] = 'Alchemy\\Phrasea\\Model\\Proxies'; $this['orm.ems'] = $this->share($this->extend('orm.ems', function (\Pimple $ems, $app) { GedmoExtension::registerAnnotations(); foreach ($ems->keys() as $key) { $app['orm.annotation.register']($key); $connection = $ems[$key]->getConnection(); $app['connection.pool.manager']->add($connection); $types = $app['orm.ems.options'][$key]['types']; $app['dbal.type.register']($connection, $types); } return $ems; })); }
/** * @inheritdoc */ protected static function _init_metadata($config, $connection_settings) { $type = \Arr::get($connection_settings, 'metadata_driver', 'annotation'); if (!array_key_exists($type, static::$metadata_drivers)) { throw new DoctrineException('Invalid Doctrine2 metadata driver: ' . $type); } if ($type == 'annotation') { // Register the doctrine annotations AnnotationRegistry::registerFile(realpath(VENDORPATH) . '/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'); // Symfony Validator annotations AnnotationRegistry::registerAutoloadNamespace('Symfony\\Component\\Validator\\Constraints', array(realpath(VENDORPATH) . '/symfony/validator', PKGPATH . 'cmf/classes')); // Create cached annotation reader $cachedAnnotationReader = new CachedReader(new AnnotationReader(), $config->getMetadataCacheImpl()); // Create a driver chain for metadata reading $driverChain = new MappingDriverChain(); // Initialise Gedmo with the driver chain and reader DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $cachedAnnotationReader); // Create the annotation driver $annotationDriver = new AnnotationDriver($cachedAnnotationReader, \Arr::get($connection_settings, 'metadata_path', array())); // Add the driver for the configured namespaces $namespaces = array_unique(\Arr::get($connection_settings, 'entity_namespaces', array())); foreach ($namespaces as $namespace) { $driverChain->addDriver($annotationDriver, $namespace); } // And set it as the default driver for good measure $driverChain->setDefaultDriver($annotationDriver); return $driverChain; } $class = '\\Doctrine\\ORM\\Mapping\\Driver\\' . static::$metadata_drivers[$type]; return new $class($connection_settings['metadata_path']); }
/** * Enable Gedmo Doctrine Extensions * * @param array $namespaces * @param bool $all */ public function bootGedmoExtensions($namespaces = ['App'], $all = true) { if ($all) { DoctrineExtensions::registerMappingIntoDriverChainORM($this->chain, $this->reader); } else { DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($this->chain, $this->reader); } $driver = $this->metadata->getMetadataDriverImpl(); foreach ($namespaces as $namespace) { $this->chain->addDriver($driver, $namespace); } $this->metadata->setMetadataDriverImpl($this->chain); $this->dispatcher->fire('doctrine.driver-chain::booted', [$driver, $this->chain]); }
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; use Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider; $app = new Application(); $app['profiling.start'] = microtime(true); $app->register(new MonologServiceProvider(), ['monolog.logfile' => __DIR__ . '/../var/logs/prod.log', 'monolog.level' => Logger::ERROR]); $app->register(new ServiceControllerServiceProvider()); $app->register(new SerializerServiceProvider()); $app['serializer.normalizers'] = $app->share(function () { return [new PropertyNormalizer(new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())))]; }); $app->register(new DoctrineServiceProvider(), ['db.options' => ['driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => 'gis', 'user' => 'root', 'password' => 'test', 'charset' => 'utf8mb4']]); $app->register(new DoctrineOrmServiceProvider(), ['orm.proxies_dir' => __DIR__ . '/Gis/Proxy', 'orm.default_cache' => 'apc', 'orm.em.options' => ['mappings' => [['type' => 'annotation', 'namespace' => 'Gis\\Entity', 'path' => __DIR__ . '/Gis/Entity', 'use_simple_annotation_reader' => false]]], 'orm.custom.functions.numeric' => ['DISTANCE' => 'Gis\\Doctrine\\Query\\Mysql\\Distance']]); $app->register(new UrlGeneratorServiceProvider()); $app->get('/', function () use($app) { return $app->redirect('/api/v1'); }); $apiProvider = new ApiProvider(); $app->register($apiProvider); $app->mount('/api/v1', $apiProvider); $app->error(function (\Exception $e, $code) use($app) { $app['monolog']->addError($e->getMessage()); $app['monolog']->addError($e->getTraceAsString()); return new Response($app['serializer']->serialize(ResponseMeta::error($e->getMessage()), $app['request']->getRequestFormat('json')), Response::HTTP_INTERNAL_SERVER_ERROR); }); AnnotationRegistry::registerFile(__DIR__ . '/../vendor/symfony/serializer/Annotation/Groups.php'); DoctrineExtensions::registerAnnotations(); $treeListener = new TreeListener(); $app['db.event_manager']->addEventSubscriber($treeListener); return $app;
/** * * @return EntityManager */ public function getEntityManager() { $cache = new DoctrineCache\ArrayCache(); $annotationReader = new AnnotationReader(); $cachedAnnotationReader = new CachedReader($annotationReader, $cache); // create a driver chain for metadata reading $driverChain = new MappingDriverChain(); // load superclass metadata mapping only, into driver chain // also registers Gedmo annotations.NOTE: you can personalize it Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $cachedAnnotationReader); // now we want to register our application entities, // for that we need another metadata driver used for Entity namespace $annotationDriver = new AnnotationDriver($cachedAnnotationReader, $this->paths); $driverChain->addDriver($annotationDriver, $this->namespace); // general ORM configuration $isDevMode = $this->env != "production"; $config = DoctrineSetup::createAnnotationMetadataConfiguration($this->paths, $isDevMode); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); $config->setMetadataDriverImpl($driverChain); $config->setProxyDir($this->proxy_path); $config->setProxyNamespace($this->namespace . '\\Proxy'); $config->setAutoGenerateProxyClasses($isDevMode); // Third, create event manager and hook prefered extension listeners $evm = new EventManager(); // gedmo extension listeners // 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); // tree $treeListener = new Gedmo\Tree\TreeListener(); $treeListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($treeListener); // loggable, not used in example $loggableListener = new Gedmo\Loggable\LoggableListener(); $loggableListener->setAnnotationReader($cachedAnnotationReader); $loggableListener->setUsername('unknown'); $evm->addEventSubscriber($loggableListener); // timestampable $timestampableListener = new Gedmo\Timestampable\TimestampableListener(); $timestampableListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($timestampableListener); // blameable $blameableListener = new Gedmo\Blameable\BlameableListener(); $blameableListener->setAnnotationReader($cachedAnnotationReader); $blameableListener->setUserValue('unknown'); // determine from your environment $evm->addEventSubscriber($blameableListener); // translatable - buggy !!! /* $translatableListener = new Gedmo\Translatable\TranslatableListener(); // current translation locale should be set from session or hook later into the listener // most important, before entity manager is flushed $translatableListener->setTranslatableLocale('en'); $translatableListener->setDefaultLocale('en'); $translatableListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($translatableListener); */ // sortable, not used in example $sortableListener = new Gedmo\Sortable\SortableListener(); $sortableListener->setAnnotationReader($cachedAnnotationReader); $evm->addEventSubscriber($sortableListener); // mysql set names UTF-8 if required $evm->addEventSubscriber(new \Doctrine\DBAL\Event\Listeners\MysqlSessionInit()); // Finally, create entity manager return EntityManager::create($this->dbParams, $config, $evm); }