Advertisement
Guest User

Untitled

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