Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //File:/myproject/libs/MyLib/Doctrine2/EntityManagerManager.php
- namespace Nautic\Doctrine2;
- /**
- *
- * Manager Class to manage multiple instances of \Doctrine\ORM\EntityManager
- * Supports lazy loading of EntityManager instance by configuration
- * @author Schnueggel
- *
- */
- class EntityManagerManager {
- /**
- * Default Doctrine2 Cache
- * @var \Doctrine\Common\ArrayCache
- */
- private $arrayCache;
- /**
- *
- * @var Nautic\Doctrine2\EntityManagerManager
- */
- private static $instance = null;
- /**
- *
- * $config data
- * @var array
- */
- private $configs = array();
- /**
- *
- * Array containing \Doctrine\ORM\EntityManager instances
- * @var array
- */
- private $entityManager = array();
- /**
- *
- * prevent multiple instance of EntityManagerManager
- */
- private function __construct(){}
- /**
- * Singleton pattern
- * @return Nautic\Doctrine2\EntityManagerManager
- */
- public static function getInstance(){
- if(self::$instance === null){
- self::$instance = new self();
- }
- return self::$instance;
- }
- /**
- * Add a config for a single EntityManager
- *
- * Example:
- *
- * $config = array(
- * 'metadataCacheImpl' => @see \Doctrine\Common\Cache (default:\Doctrine\Common\Cache\ArrayCache),
- * 'queryCacheImpl' => @see \Doctrine\Common\Cache (default:\Doctrine\Common\Cache\ArrayCache),
- * 'proxyDir' => 'path\to\ProxyDir',
- * 'proxyNamespace' => 'My\Proxy\NameSpace',
- * 'annotationDriverEntityPath' => 'Path\To\Entity\Dir',
- * 'conn' => array(
- * //PDO MYSQL example for other options see driver specifics \Doctrine\DBAL\DRIVER\
- * 'driver' => 'pdo_mysql',
- * 'user' => 'username',
- * 'password' => 'connection password,
- * 'dbname' => 'dbname',
- * 'host' => 'localhost'
- * ),
- * 'autoGenerateProxyClasses' => true or false(default:true),
- * 'useConnOfModule' =>moduleName \\this is a specific param of this class not of Doctrine. Set this to a module where you have already a connection defined
- * );
- *
- * @param array $config
- * @param string $module
- */
- public function addConfig(array $config, $module){
- $this->configs[$module] = $config;
- }
- /**
- *
- * Get EntityManager by module name
- * @throws InvalidArgumentException
- * @return \Doctrine\ORM\EntityManager
- */
- public function getEntityManager($module){
- if(array_key_exists($module, $this->entityManager)){
- return $this->entityManager[$module];
- }
- if(array_key_exists($module, $this->configs)){
- $em = $this->createEntityManager($this->configs[$module]);
- $this->addEntityManager($em, $module);
- return $em;
- }
- throw InvalidArgumentException('EntityManager for module '. $module . ' could not be found');
- }
- /**
- * Add EntityManager instance to this Manager by module name.
- * This will overwrite any existing instance attached to this module name!
- * @param \Doctrine\ORM\EntityManager $em
- * @param string $module
- */
- public function addEntityManager(\Doctrine\ORM\EntityManager $em,$module){
- $this->entityManager[$module] = $em;
- }
- /**
- *
- * Create \Doctrine\ORM\EntityManager from config data
- * @see \Nautic\Doctrine2\EntityManagerManager::addConfig for config options
- * @param array $config
- * @throws InvalidArgumentException
- * @return \Doctrine\ORM\EntityManager
- */
- public function createEntityManager(array $config){
- $doctrineConfig = new \Doctrine\ORM\Configuration();
- /**
- * Set the caches, use ArrayCache as default
- */
- if(array_key_exists('metadataCacheImpl', $config)){
- $doctrineConfig->setMetadataCacheImpl( new $config['metadataCacheImpl']);
- }else{
- $doctrineConfig->setMetadataCacheImpl($this->getArrayCache());
- }
- if(array_key_exists('queryCacheImpl',$config)){
- $doctrineConfig->setQueryCacheImpl( new $config['queryCacheImpl']);
- }else{
- $doctrineConfig->setQueryCacheImpl($this->getArrayCache());
- }
- /**
- * Set ProxyDir and ProxyNamespace both are required and have no defaults
- */
- if(array_key_exists('proxyDir', $config)){
- $doctrineConfig->setProxyDir($config['proxyDir']);
- }else{
- throw new InvalidArgumentException('Doctrine2 configuration error, proxyDir must be set');
- }
- if(array_key_exists('proxyNamespace', $config)){
- $doctrineConfig->setProxyNamespace($config['proxyNamespace']);
- }else{
- throw new InvalidArgumentException('Doctrine2 configuration error, proxyNamespace must be set');
- }
- /**
- * @todo Implement YAML and XML driver configuration
- */
- if( array_key_exists('annotationDriverEntityPath', $config) ){
- $driverImpl = $doctrineConfig->newDefaultAnnotationDriver(array($config['annotationDriverEntityPath']));
- }else{
- throw new Exception('Doctrine2 configuration Error annotationDriverEntityPath must be set other implementation are not supported at the moment ');
- }
- $doctrineConfig->setMetadataDriverImpl($driverImpl);
- /**
- * Setup database connection
- */
- if( array_key_exists('conn', $config) && is_array($config['conn'])){
- /**
- * Check if connection param driver exists else throw exception
- */
- if( !array_key_exists('driver',$config['conn'])){
- throw InvalidArgumentException('Doctrine2 config error, connection property (\'driver\') not found');
- }
- /**
- * Forcing use of Doctrine2 connection data keys
- */
- $connectionOptions = $config['conn'];
- }elseif( array_key_exists('useConnOfModule', $config) ){
- $_module = $config['useConnOfModule'];
- if( array_key_exists($_module, $this->configs) && array_key_exists('conn', $this->configs[$_module]) ){
- $connectionOptions = $this->configs[$_module]['conn'];
- }else{
- throw InvalidArgumentException('Doctrine2 config error, connection property useConnOfModule:'.$_module.' the connection data could not be found');
- }
- }else{
- throw InvalidArgumentException('Doctrine2 config error, connection properties not found(\'conn\')');
- }
- /**
- * Check if autoGenerateProxyClasses is set else use false as default
- */
- if(array_key_exists('autoGenerateProxyClasses', $config)){
- $doctrineConfig->setAutoGenerateProxyClasses($config['autoGenerateProxyClasses']);
- }else{
- $doctrineConfig->setAutoGenerateProxyClasses(false);
- }
- $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $doctrineConfig);
- return $em;
- }
- /**
- *
- * Clear config by key or complete
- * @param string $module
- */
- public function clearEntityManager($module = null){
- if( $module){
- unset($this->entityManager[$module]);
- }
- }
- /**
- *
- * Clear config by key or complete
- * @param string $module
- */
- public function clearConfig($module = null){
- if($module){
- unset($this->config[$module]);
- }else{
- $config = array();
- }
- }
- /**
- * Returns all created EntityManager
- * @return array
- */
- public function getAllEntityManager(){
- return $this->entityManager;
- }
- /**
- * Returns the configs for all EntityManager
- * @return array
- */
- public function getConfigs(){
- return $this->configs;
- }
- /**
- *
- * Get default ArrayCache
- * @return \Doctrine\Common\Cache\ArrayCache
- */
- protected function getArrayCache(){
- if($this->arrayCache === null){
- $this->arrayCache = new \Doctrine\Common\Cache\ArrayCache();
- }
- return $this->arrayCache;
- }
- /**
- *
- * Delete instance if their is one
- * @return void.
- */
- public static function deleteInstance(){
- self::$instance = null;
- }
- /**
- *
- * Reset state of instance
- * @return void
- */
- public function reset(){
- $this->configs = array();
- $this->entityManager = array();
- }
- }
- //FILE:/myproject/libs/MyLib/Application/Resource/Doctrine2
- /**
- *
- * Zend_Application_Resource for Doctrine2
- * This resource is rahter simple and will add the \Nautic\Doctrine2\EntityManagerManager instance to the bootstrap
- * Application config could be:
- *
- * resources.doctrine2.classloader.Doctrine = \path\to\Doctrine2\
- * resources.doctrine2.modules.app.proxyDir = \path\to\app\ProxyDir
- * resources.doctrine2.modules.app.proxyNamespace = 'My\Proxy\Namespace'
- * ....
- * resources.doctrine2.modules.default.proxyDir = \path\to\default\ProxyDir
- * ...
- *
- * @see \Nautic\Doctrine2\EntityManagerManager::addConfig() Description for more Details
- * @author christian.steinmann
- */
- class Nautic_Application_Resource_Doctrine2 extends Zend_Application_Resource_ResourceAbstract{
- /**
- * @var \Nautic\Doctrine2\EntityManagerManager
- */
- protected $manager = null;
- /**
- * Initialize \Nautic\Doctrine2\EntityManagerManager
- *
- * @return \Nautic\Doctrine2\EntityManagerManager
- */
- public function init()
- {
- $options = $this->getOptions();
- if( array_key_exists('classloader', $options) ){
- if(is_array($options['classloader'])){
- foreach($options['classloader'] as $namespace=>$includepath){
- $classLoader = new \Doctrine\Common\ClassLoader($namespace, $includepath);
- $classLoader->register();
- }
- }
- }
- return $this->getEntityManagerManager();
- }
- /**
- * Get \Nautic\Doctrine2\EntityManagerManager instance
- * @return \Nautic\Doctrine2\EntityManagerManager
- */
- public function getEntityManagerManager(){
- if( null === $this->manager ){
- $options = $this->getOptions();
- $emm = \Nautic\Doctrine2\EntityManagerManager::getInstance();
- if( array_key_exists('modules', $options) && is_array($options['modules'])){
- foreach($options['modules'] as $module => $config){
- $emm->addConfig($config, $module);
- }
- }
- $this->manager = $emm;
- }
- return $emm;
- }
- }
- //FILE:/myproject/application/config/application.ini
- [live]
- appnamespace = "App"
- pluginpaths.MyLib_Application_Resource = "MyLib/Application/Resource"
- resources.doctrine2.modules.app.conn.host = 'localhost'
- resources.doctrine2.modules.app.conn.user = 'root'
- resources.doctrine2.modules.app.conn.password = 'root'
- resources.doctrine2.modules.app.conn.driver = 'pdo_mysql'
- resources.doctrine2.modules.app.conn.dbname = 'test'
- resources.doctrine2.modules.app.annotationDriverEntityPath = APPLICATION_PATH'/models/doctrine/entities'
- resources.doctrine2.modules.app.proxyNamespace = 'models\doctrine\proxies'
- resources.doctrine2.modules.app.proxyDir = APPLICATION_PATH'/models/doctrine/proxies'
- resources.doctrine2.modules.app.queryCacheImpl = 'Doctrine\Common\Cache\ApcCache'
- resources.doctrine2.modules.app.metadataCacheImpl = 'Doctrine\Common\Cache\ApcCache'
- resources.doctrine2.modules.app.autoGenerateProxyClasses = 0
- resources.doctrine2.modules.default.useConnOfModule = app
- resources.doctrine2.modules.default.annotationDriverEntityPath = APPLICATION_PATH'/eadefaultodels/doctrine/entities'
- resources.doctrine2.modules.default.proxyNamespace = 'default\models\doctrine\proxies'
- resources.doctrine2.modules.default.proxyDir = APPLICATION_PATH'/default/models/doctrine/proxies'
- resources.doctrine2.modules.default.queryCacheImpl = 'Doctrine\Common\Cache\ApcCache'
- resources.doctrine2.modules.default.metadataCacheImpl = 'Doctrine\Common\Cache\ApcCache'
- resources.doctrine2.modules.default.autoGenerateProxyClasses = 0
- [dev:live]
- resources.db.params.dbname = test_local
- resources.doctrine2.modules.app.conn.dbname = test_local
- resources.frontController.throwExceptions = true
- resources.doctrine2.modules.default.autoGenerateProxyClasses = 1
- //FILE: /myprojekt/bin/doctrine_default.php
- /**
- * Script to create Proxyclasses in every module
- **/
- print 'Using Enviroment "dev" for Application boostrap'.PHP_EOL;
- define('APPLICATION_ENV', 'dev');
- define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
- set_include_path(implode(PATH_SEPARATOR, array(
- realpath(APPLICATION_PATH . '/../library'),
- get_include_path(),
- )));
- require_once 'Zend/Application.php';
- // Create application, bootstrap, and run
- $application = new Zend_Application(
- APPLICATION_ENV,
- APPLICATION_PATH . '/config/application.ini'
- );
- $application->getBootstrap()->bootstrap();
- $doctrine2 = $application->getBootstrap()->getResource('doctrine2');
- /**
- * Get EntityManager for specific module
- */
- /* @var $em \Doctrine\ORM\EntityManager */
- $em = $doctrine2->getEntityManager('default');
- print 'ProxyDir: ' .$em->getConfiguration()->getProxyDir().PHP_EOL;
- print 'EntityDir: ' .print_r($em->getConfiguration()->getMetadataDriverImpl()->getPaths(),true) . PHP_EOL;
- /**
- * Set Class loading for Symfony namespace within Doctrine namespace
- * Doctrine\Symfony\Component\Console\Helper\HelperSet() instead of Doctrine\Symfony\Component\Console\Helper\HelperSet()
- */
- $classLoader = new DoctrineCommonClassLoader('Symfony', 'Doctrine');
- $classLoader->register();
- $helperSet = new SymfonyComponentConsoleHelperHelperSet();
- $helperSet->set( new DoctrineDBALToolsConsoleHelperConnectionHelper($em->getConnection()),'db');
- $helperSet->set( new DoctrineORMToolsConsoleHelperEntityManagerHelper($em),'em');
- $cli = new SymfonyComponentConsoleApplication('Doctrine Command Line Interface', DoctrineORMVersion::VERSION);
- $cli->setCatchExceptions(true);
- $cli->setHelperSet($helperSet);
- $cli->addCommands(array(
- // DBAL Commands
- new DoctrineDBALToolsConsoleCommandRunSqlCommand(),
- new DoctrineDBALToolsConsoleCommandImportCommand(),
- // ORM Commands
- new DoctrineORMToolsConsoleCommandClearCacheMetadataCommand(),
- new DoctrineORMToolsConsoleCommandClearCacheResultCommand(),
- new DoctrineORMToolsConsoleCommandClearCacheQueryCommand(),
- new DoctrineORMToolsConsoleCommandSchemaToolCreateCommand(),
- new DoctrineORMToolsConsoleCommandSchemaToolUpdateCommand(),
- new DoctrineORMToolsConsoleCommandSchemaToolDropCommand(),
- new DoctrineORMToolsConsoleCommandEnsureProductionSettingsCommand(),
- new DoctrineORMToolsConsoleCommandConvertDoctrine1SchemaCommand(),
- new DoctrineORMToolsConsoleCommandGenerateRepositoriesCommand(),
- new DoctrineORMToolsConsoleCommandGenerateEntitiesCommand(),
- new DoctrineORMToolsConsoleCommandGenerateProxiesCommand(),
- new DoctrineORMToolsConsoleCommandConvertMappingCommand(),
- new DoctrineORMToolsConsoleCommandRunDqlCommand(),
- new DoctrineORMToolsConsoleCommandValidateSchemaCommand(),
- ));
- $cli->run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement