Advertisement
Guest User

Untitled

a guest
Jul 30th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.32 KB | None | 0 0
  1. <?php
  2. //File:/myproject/libs/MyLib/Doctrine2/EntityManagerManager.php
  3. /**
  4.  *
  5.  * Manager Class to manage multiple instances of \Doctrine\ORM\EntityManager
  6.  * Supports lazy loading of EntityManager instance by configuration
  7.  * @author Schnueggel
  8.  *
  9.  */
  10. class Nautic_Doctrine2_EntityManagerManager {
  11.  
  12.     /**
  13.      * Default Doctrine2 Cache
  14.      * @var \Doctrine\Common\ArrayCache
  15.      */
  16.     private $arrayCache;
  17.     /**
  18.      *
  19.      * @var Nautic\Doctrine2\EntityManagerManager
  20.      */
  21.     private static $instance = null;
  22.     /**
  23.      *
  24.      * $config data
  25.      * @var array
  26.      */
  27.     private $configs = array();
  28.  
  29.     /**
  30.      *
  31.      * Array containing \Doctrine\ORM\EntityManager instances
  32.      * @var array
  33.      */
  34.     private $entityManager = array();
  35.  
  36.     /**
  37.      *
  38.      * prevent multiple instance of EntityManagerManager
  39.      */
  40.     private function __construct(){}
  41.  
  42.     /**
  43.      * Singleton pattern
  44.      * @return Nautic\Doctrine2\EntityManagerManager
  45.      */
  46.     public static function getInstance(){
  47.         if(self::$instance === null){
  48.             self::$instance = new self();
  49.         }
  50.         return self::$instance;
  51.     }
  52.  
  53.     /**
  54.      * Add a config for a single EntityManager
  55.      *
  56.      * Example:
  57.      *
  58.      *  $config = array(
  59.      *      'metadataCacheImpl' => @see \Doctrine\Common\Cache (default:\Doctrine\Common\Cache\ArrayCache),
  60.      *      'queryCacheImpl' => @see \Doctrine\Common\Cache (default:\Doctrine\Common\Cache\ArrayCache),
  61.      *      'proxyDir' => 'path\to\ProxyDir',
  62.      *      'proxyNamespace' => 'My\Proxy\NameSpace',
  63.      *      'annotationDriverEntityPath' => 'Path\To\Entity\Dir',
  64.      *      'conn' => array(
  65.      *          //PDO MYSQL example for other options see driver specifics \Doctrine\DBAL\DRIVER\
  66.      *          'driver'    => 'pdo_mysql',
  67.      *          'user'      => 'username',
  68.      *          'password'  => 'connection password,
  69.      *          'dbname'    => 'dbname',
  70.      *          'host'      => 'localhost'
  71.      *          ),
  72.      *      'autoGenerateProxyClasses' => true or false(default:true),
  73.      *      'useConnOfModule' =>moduleName \\this is a specific param of this class not of Doctrine. Set this to a doctrine entitiymanager module where you have already a connection defined.
  74.      *  );
  75.      *
  76.      * @param array $config
  77.      * @param string $module
  78.      */
  79.     public function addConfig(array $config, $module){
  80.         $this->configs[$module] = $config;
  81.     }
  82.  
  83.     /**
  84.      *
  85.      * Get EntityManager by module name
  86.      * @throws InvalidArgumentException
  87.      * @return \Doctrine\ORM\EntityManager
  88.      */
  89.     public function getEntityManager($module){
  90.         if(array_key_exists($module, $this->entityManager)){
  91.             return $this->entityManager[$module];
  92.         }
  93.         if(array_key_exists($module, $this->configs)){
  94.             $em = $this->createEntityManager($this->configs[$module]);
  95.             $this->addEntityManager($em, $module);
  96.             return $em;
  97.         }
  98.         throw InvalidArgumentException('EntityManager for module '. $module . ' could not be found');
  99.     }
  100.  
  101.     /**
  102.      * Add EntityManager instance to this Manager by module name.
  103.      * This will overwrite any existing instance attached to this module name!
  104.      * @param \Doctrine\ORM\EntityManager $em
  105.      * @param string $module
  106.      */
  107.     public function addEntityManager(\Doctrine\ORM\EntityManager $em,$module){
  108.         $this->entityManager[$module] = $em;
  109.     }
  110.  
  111.     /**
  112.      *
  113.      * Create \Doctrine\ORM\EntityManager from config data
  114.      * @see \Nautic\Doctrine2\EntityManagerManager::addConfig for config options
  115.      * @param array $config
  116.      * @throws InvalidArgumentException
  117.      * @return \Doctrine\ORM\EntityManager
  118.      */
  119.     public function createEntityManager(array $config){
  120.  
  121.          
  122.         $doctrineConfig = new \Doctrine\ORM\Configuration();
  123.  
  124.         /**
  125.          * Set the caches, use ArrayCache as default
  126.          */
  127.         if(array_key_exists('metadataCacheImpl', $config)){
  128.             $doctrineConfig->setMetadataCacheImpl( new $config['metadataCacheImpl']);
  129.         }else{
  130.             $doctrineConfig->setMetadataCacheImpl($this->getArrayCache());
  131.         }
  132.  
  133.         if(array_key_exists('queryCacheImpl',$config)){
  134.             $doctrineConfig->setQueryCacheImpl( new $config['queryCacheImpl']);
  135.         }else{
  136.             $doctrineConfig->setQueryCacheImpl($this->getArrayCache());
  137.         }
  138.  
  139.         /**
  140.          * Set ProxyDir and ProxyNamespace both are required and have no defaults
  141.          */
  142.         if(array_key_exists('proxyDir', $config)){
  143.             $doctrineConfig->setProxyDir($config['proxyDir']);
  144.         }else{
  145.             throw new InvalidArgumentException('Doctrine2 configuration error, proxyDir must be set');
  146.         }
  147.  
  148.         if(array_key_exists('proxyNamespace', $config)){
  149.             $doctrineConfig->setProxyNamespace($config['proxyNamespace']);
  150.         }else{
  151.             throw new InvalidArgumentException('Doctrine2 configuration error, proxyNamespace must be set');
  152.         }
  153.  
  154.         /**
  155.          * @todo Implement YAML and XML driver configuration
  156.          */
  157.         if( array_key_exists('annotationDriverEntityPath', $config) ){
  158.             $driverImpl = $doctrineConfig->newDefaultAnnotationDriver(array($config['annotationDriverEntityPath']));
  159.         }else{
  160.             throw new Exception('Doctrine2 configuration Error annotationDriverEntityPath must be set other implementation are not supported at the moment ');
  161.         }
  162.  
  163.         $doctrineConfig->setMetadataDriverImpl($driverImpl);
  164.         /**
  165.          * Setup database connection
  166.          */
  167.         if( array_key_exists('conn', $config) && is_array($config['conn'])){
  168.             /**
  169.              * Check if connection param driver exists else throw exception
  170.              */
  171.             if( !array_key_exists('driver',$config['conn'])){
  172.                 throw InvalidArgumentException('Doctrine2 config error, connection property (\'driver\') not found');
  173.             }
  174.             /**
  175.              * Forcing use of Doctrine2 connection data keys
  176.              */
  177.             $connectionOptions = $config['conn'];
  178.              
  179.         }elseif( array_key_exists('useConnOfModule', $config) ){
  180.             $_module = $config['useConnOfModule'];
  181.             if( array_key_exists($_module, $this->configs) && array_key_exists('conn', $this->configs[$_module]) ){
  182.                 $connectionOptions = $this->configs[$_module]['conn'];
  183.             }else{
  184.                 throw InvalidArgumentException('Doctrine2 config error, connection property useConnOfModule:'.$_module.' the connection data could not be found');
  185.             }
  186.         }else{
  187.             throw InvalidArgumentException('Doctrine2 config error, connection properties not found(\'conn\')');
  188.         }
  189.        
  190.         /**
  191.          * Check if autoGenerateProxyClasses is set else use false as default
  192.          */
  193.         if(array_key_exists('autoGenerateProxyClasses', $config)){
  194.             $doctrineConfig->setAutoGenerateProxyClasses($config['autoGenerateProxyClasses']);
  195.         }else{
  196.             $doctrineConfig->setAutoGenerateProxyClasses(false);
  197.         }
  198.  
  199.         $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $doctrineConfig);
  200.  
  201.         return $em;
  202.     }
  203.  
  204.     /**
  205.      *
  206.      * Clear config by key or complete
  207.      * @param string $module
  208.      */
  209.     public function clearEntityManager($module = null){
  210.         if( $module){
  211.             unset($this->entityManager[$module]);
  212.         }
  213.     }
  214.     /**
  215.      *
  216.      * Clear config by key or complete
  217.      * @param string $module
  218.      */
  219.     public function clearConfig($module = null){
  220.         if($module){
  221.             unset($this->config[$module]);
  222.         }else{
  223.             $config = array();
  224.         }
  225.     }
  226.    
  227.     /**
  228.      * Returns all created EntityManager
  229.      * @return array
  230.      */
  231.     public function getAllEntityManager(){
  232.         return $this->entityManager;
  233.     }
  234.    
  235.     /**
  236.      * Returns the configs for all EntityManager
  237.      * @return array
  238.      */
  239.     public function getConfigs(){
  240.         return $this->configs;
  241.     }
  242.  
  243.     /**
  244.      *
  245.      * Get default ArrayCache
  246.      * @return \Doctrine\Common\Cache\ArrayCache
  247.      */
  248.     protected function getArrayCache(){
  249.         if($this->arrayCache ===  null){
  250.             $this->arrayCache = new \Doctrine\Common\Cache\ArrayCache();
  251.         }
  252.         return $this->arrayCache;
  253.     }
  254.    
  255.     /**
  256.      *
  257.      * Delete instance if their is one
  258.      * @return void.
  259.      */
  260.     public static function deleteInstance(){
  261.             self::$instance = null;
  262.     }
  263.    
  264.     /**
  265.      *
  266.      * Reset state of instance
  267.      * @return void
  268.      */
  269.     public function reset(){
  270.         $this->configs = array();
  271.         $this->entityManager = array();
  272.     }
  273. }
  274.  
  275.  
  276. //FILE:/myproject/libs/MyLib/Application/Resource/Doctrine2
  277.  
  278. /**
  279.  *
  280.  * Zend_Application_Resource for Doctrine2
  281.  * This resource is rahter simple and will add the \Nautic\Doctrine2\EntityManagerManager instance to the bootstrap
  282.  * Application config could be:
  283.  *
  284.  * resources.doctrine2.classloader.Doctrine = \path\to\Doctrine2\
  285.  * resources.doctrine2.modules.app.proxyDir = \path\to\app\ProxyDir
  286.  * resources.doctrine2.modules.app.proxyNamespace = 'My\Proxy\Namespace'
  287.  * ....
  288.  * resources.doctrine2.modules.default.proxyDir = \path\to\default\ProxyDir
  289.  * ...
  290.  *
  291.  * @see \Nautic\Doctrine2\EntityManagerManager::addConfig() Description for more Details
  292.  * @author christian.steinmann
  293.  */
  294. class Nautic_Application_Resource_Doctrine2 extends Zend_Application_Resource_ResourceAbstract{
  295.  
  296.     /**
  297.      * @var \Nautic\Doctrine2\EntityManagerManager
  298.      */
  299.     protected $manager = null;
  300.  
  301.     /**
  302.      * Initialize  \Nautic\Doctrine2\EntityManagerManager
  303.      *
  304.      * @return \Nautic\Doctrine2\EntityManagerManager
  305.      */
  306.     public function init()
  307.     {
  308.         $options = $this->getOptions();
  309.         if( array_key_exists('classloader', $options) ){
  310.             if(is_array($options['classloader'])){
  311.                 foreach($options['classloader'] as $namespace=>$includepath){
  312.                     $classLoader = new \Doctrine\Common\ClassLoader($namespace, $includepath);
  313.             $classLoader->register();
  314.                 }
  315.             }
  316.         }
  317.         return $this->getEntityManagerManager();
  318.     }
  319.    
  320.     /**
  321.      * Get \Nautic\Doctrine2\EntityManagerManager instance
  322.      * @return \Nautic\Doctrine2\EntityManagerManager
  323.      */
  324.     public function getEntityManagerManager(){
  325.         if( null === $this->manager ){
  326.             $options = $this->getOptions();
  327.             $emm = \Nautic\Doctrine2\EntityManagerManager::getInstance();
  328.            
  329.             if( array_key_exists('modules', $options) && is_array($options['modules'])){
  330.                
  331.                 foreach($options['modules'] as $module => $config){
  332.                     $emm->addConfig($config, $module);
  333.                 }
  334.             }
  335.             $this->manager = $emm;
  336.         }
  337.         return $emm;
  338.     }
  339. }
  340.  
  341. //FILE:/myproject/application/config/application.ini
  342.  
  343. [live]
  344.  
  345. appnamespace = "App"
  346.  
  347. pluginpaths.MyLib_Application_Resource = "MyLib/Application/Resource"
  348.  
  349. resources.doctrine2.modules.app.conn.host = 'localhost'
  350. resources.doctrine2.modules.app.conn.user = 'root'
  351. resources.doctrine2.modules.app.conn.password = 'root'
  352. resources.doctrine2.modules.app.conn.driver = 'pdo_mysql'
  353. resources.doctrine2.modules.app.conn.dbname = 'test'
  354. resources.doctrine2.modules.app.annotationDriverEntityPath = APPLICATION_PATH'/models/doctrine/entities'
  355. resources.doctrine2.modules.app.proxyNamespace = 'models\doctrine\proxies'
  356. resources.doctrine2.modules.app.proxyDir = APPLICATION_PATH'/models/doctrine/proxies'
  357. resources.doctrine2.modules.app.queryCacheImpl = 'Doctrine\Common\Cache\ApcCache'
  358. resources.doctrine2.modules.app.metadataCacheImpl = 'Doctrine\Common\Cache\ApcCache'
  359. resources.doctrine2.modules.app.autoGenerateProxyClasses = 0
  360.  
  361. resources.doctrine2.modules.default.useConnOfModule = app
  362. resources.doctrine2.modules.default.annotationDriverEntityPath = APPLICATION_PATH'/default/models/doctrine/entities'
  363. resources.doctrine2.modules.default.proxyNamespace = 'default\models\doctrine\proxies'
  364. resources.doctrine2.modules.default.proxyDir = APPLICATION_PATH'/default/models/doctrine/proxies'
  365. resources.doctrine2.modules.default.queryCacheImpl = 'Doctrine\Common\Cache\ApcCache'
  366. resources.doctrine2.modules.default.metadataCacheImpl = 'Doctrine\Common\Cache\ApcCache'
  367. resources.doctrine2.modules.default.autoGenerateProxyClasses = 0
  368.  
  369.  
  370. [dev:live]
  371.  
  372. resources.db.params.dbname = test_local
  373. resources.doctrine2.modules.app.conn.dbname = test_local
  374. resources.frontController.throwExceptions = true
  375. resources.doctrine2.modules.default.autoGenerateProxyClasses = 1
  376.  
  377.  
  378. //FILE: /myprojekt/bin/doctrine_default.php
  379. /**
  380.  * Script to create Proxyclasses in every module
  381. **/
  382.  
  383. print 'Using Enviroment "dev" for Application boostrap'.PHP_EOL;
  384.  
  385. define('APPLICATION_ENV', 'dev');
  386.  
  387. define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
  388.  
  389. set_include_path(implode(PATH_SEPARATOR, array(
  390.     realpath(APPLICATION_PATH . '/../library'),
  391.     get_include_path(),
  392. )));
  393.  
  394. require_once 'Zend/Application.php';
  395.  
  396. // Create application, bootstrap, and run
  397. $application = new Zend_Application(
  398.     APPLICATION_ENV,
  399.     APPLICATION_PATH . '/config/application.ini'
  400. );
  401.  
  402. $application->getBootstrap()->bootstrap();
  403.  
  404. $doctrine2 = $application->getBootstrap()->getResource('doctrine2');
  405. /**
  406.  * Get EntityManager for specific module
  407.  */
  408. /* @var $em \Doctrine\ORM\EntityManager */
  409. $em = $doctrine2->getEntityManager('default');
  410.  
  411. print 'ProxyDir: ' .$em->getConfiguration()->getProxyDir().PHP_EOL;
  412. print 'EntityDir: ' .print_r($em->getConfiguration()->getMetadataDriverImpl()->getPaths(),true) . PHP_EOL;
  413.  
  414. /**
  415.  * Set Class loading for Symfony namespace within Doctrine namespace
  416.  * Doctrine\Symfony\Component\Console\Helper\HelperSet() instead of Doctrine\Symfony\Component\Console\Helper\HelperSet()
  417.  */
  418. $classLoader = new DoctrineCommonClassLoader('Symfony', 'Doctrine');
  419. $classLoader->register();
  420.  
  421.  
  422. $helperSet =  new SymfonyComponentConsoleHelperHelperSet();
  423. $helperSet->set( new DoctrineDBALToolsConsoleHelperConnectionHelper($em->getConnection()),'db');
  424. $helperSet->set( new DoctrineORMToolsConsoleHelperEntityManagerHelper($em),'em');
  425.  
  426. $cli = new SymfonyComponentConsoleApplication('Doctrine Command Line Interface', DoctrineORMVersion::VERSION);
  427. $cli->setCatchExceptions(true);
  428. $cli->setHelperSet($helperSet);
  429. $cli->addCommands(array(
  430.     // DBAL Commands
  431.     new DoctrineDBALToolsConsoleCommandRunSqlCommand(),
  432.     new DoctrineDBALToolsConsoleCommandImportCommand(),    
  433.     // ORM Commands
  434.     new DoctrineORMToolsConsoleCommandClearCacheMetadataCommand(),
  435.     new DoctrineORMToolsConsoleCommandClearCacheResultCommand(),
  436.     new DoctrineORMToolsConsoleCommandClearCacheQueryCommand(),
  437.     new DoctrineORMToolsConsoleCommandSchemaToolCreateCommand(),
  438.     new DoctrineORMToolsConsoleCommandSchemaToolUpdateCommand(),
  439.     new DoctrineORMToolsConsoleCommandSchemaToolDropCommand(),
  440.     new DoctrineORMToolsConsoleCommandEnsureProductionSettingsCommand(),
  441.     new DoctrineORMToolsConsoleCommandConvertDoctrine1SchemaCommand(),
  442.     new DoctrineORMToolsConsoleCommandGenerateRepositoriesCommand(),
  443.     new DoctrineORMToolsConsoleCommandGenerateEntitiesCommand(),
  444.     new DoctrineORMToolsConsoleCommandGenerateProxiesCommand(),
  445.     new DoctrineORMToolsConsoleCommandConvertMappingCommand(),
  446.     new DoctrineORMToolsConsoleCommandRunDqlCommand(),
  447.     new DoctrineORMToolsConsoleCommandValidateSchemaCommand(),
  448. ));
  449.  
  450. $cli->run();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement