Wildkat-YiiExt-DoctrineOrm
[ class tree: Wildkat-YiiExt-DoctrineOrm ] [ index: Wildkat-YiiExt-DoctrineOrm ] [ all elements ]

Source for file DoctrineContainer.php

Documentation is available at DoctrineContainer.php

  1. <?php
  2.  
  3. namespace Wildkat\YiiExt\DoctrineOrm;
  4.  
  5. use Doctrine\DBAL,
  6.     Doctrine\ORM,
  7.     Doctrine\Common\Cache,
  8.     Doctrine\Common\ClassLoader,
  9.     Doctrine\Common\Annotations\AnnotationReader,
  10.     Doctrine\ORM\Mapping\Driver\AnnotationDriver;
  11.  
  12. require_once 'vendor/Doctrine/Common/ClassLoader.php';
  13.  
  14. /**
  15.  * DoctrineContainer.
  16.  *
  17.  * This Yii application component acts as a container for the Doctrine 2 ORM
  18.  * library. Firstly, you will need to download the latest version of the Doctrine 2 ORM
  19.  * library and place it inside ext.Wildkat.YiiExt.DoctrineOrm.vendors. The directory
  20.  * layout should look like the following;
  21.  *
  22.  * <pre>
  23.  * DoctrineOrm/
  24.  *   - vendor/
  25.  *       - Doctrine/
  26.  *           - Common/
  27.  *           - DBAL/
  28.  *           - ORM/
  29.  *       - Symfony/
  30.  * </pre>
  31.  *
  32.  *
  33.  * Now, inside main.php config file, set up the component with 3 keys
  34.  * (dbal, entityManager & cache) where each key represents a configuration
  35.  * set for each D2 component. For example;
  36.  *
  37.  * <pre>
  38.  * 'components' => array(
  39.  *     'doctrine' => array(
  40.  *            'dbal' => array(
  41.  *                [multiple dbal configurations here]
  42.  *            ),
  43.  *            'entityManager' => array(
  44.  *                [multiple entity manager configurations here]
  45.  *            ),
  46.  *            'cache' => array(
  47.  *                [multiple cache configurations here]
  48.  *            ),
  49.  *     ),
  50.  * )
  51.  * </pre>
  52.  *
  53.  * You must also set and alias for the Wildkat namespace. At the top of the main.php
  54.  * configuration file, put
  55.  * Yii::setPathOfAlias('Wildkat', realpath(dirname(__FILE__) . '/../extensions/Wildkat'));
  56.  *
  57.  * For each D2 component, you can specify any number of configurations and index
  58.  * them numerically or with a string. You can then access each configuration
  59.  * through the component method e.g. Yii::app()->doctrine->getConnection('foo')
  60.  * returns a dbal connection with a configuration index of 'foo'.
  61.  *
  62.  * @category YiiExtensions
  63.  * @package  Wildkat\YiiExt\DoctrineOrm
  64.  * @author   Kevin Bradwick <kevin@wildk.at>
  65.  * @license  New BSD http://www.opensource.org/licenses/bsd-license.php
  66.  * @version  Release: ##VERSION##
  67.  * @link     http://www.wildk.at
  68.  */
  69. class DoctrineContainer extends \CApplicationComponent
  70. {
  71.     /**
  72.      * List of dbal configurations. Each configuration has the following options
  73.      * @link http://www.doctrine-project.org/docs/dbal/2.0/en/reference/configuration.html
  74.      *  See the Doctrine Documentation for an explanation of connection parameters
  75.      * @var array 
  76.      */
  77.     public $dbal;
  78.  
  79.     /**
  80.      * List of cache configurations. Each with the following options
  81.      * <ul>
  82.      *   <li>driver - (string) the driver e.g. ApcCache, MemcacheCache</li>
  83.      *   <li>namespace - (string) the cache namespace</li>
  84.      *   <li>servers - (array) used for memcache</li>
  85.      * </ul>
  86.      * @var array 
  87.      */
  88.     public $cache;
  89.  
  90.     /**
  91.      * List of entity manager configurations. Each with the following options
  92.      * <ul>
  93.      *   <li>connection - (string) the dbal config name</li>
  94.      *   <li>mappingDriver - (string) [AnnotationDriver, YamlDriver, XmlDriver]</li>
  95.      *   <li>mappingPaths - (array) An array of paths to find mapping information</li>
  96.      *   <li>mappingDriverOptions - (array) Additional mapping driver options
  97.      *   defined in and array and make reference to each of the drivers set
  98.      *   methods</li>
  99.      *   <li>metadataCache - (string) the cache configuration for metadata</li>
  100.      *   <li>queryCache - (string) the cache configuration for query conversions</li>
  101.      *   <li>resultCache - (string) the cache configuration for results</li>
  102.      *   <li>proxyDir - (string)the directory location for proxy classes</li>
  103.      *   <li>proxyNamespace - (string) the proxy namespace</li>
  104.      *   <li>entityNamespaces - (array) entity namespaces</li>
  105.      *   <li>autoGenerateProxyClasses - (bool) true false</li>
  106.      * </ul>
  107.      * @var array 
  108.      */
  109.     public $entityManager;
  110.  
  111.     /**
  112.      * Cached component instances
  113.      * @var array 
  114.      */
  115.     private $_cache;
  116.  
  117.     /**
  118.      * Component initialization.
  119.      *
  120.      * This method registers doctrine's autoloaders by pushing them on the
  121.      * current autoloader stack.
  122.      *
  123.      * @return null 
  124.      * @see    CApplicationComponent::init()
  125.      */
  126.     public function init()
  127.     {
  128.         $classLoader new ClassLoader('Doctrine'dirname(__FILE__'/vendor');
  129.         \Yii::registerAutoloader(array($classLoader'loadClass'));
  130.  
  131.         $classLoader new ClassLoader('Symfony'dirname(__FILE__'/vendor');
  132.         \Yii::registerAutoloader(array($classLoader'loadClass'));
  133.  
  134.     }//end init()
  135.  
  136.     /**
  137.      * Get an instance of a DBAL Connection
  138.      *
  139.      * @param sting $name the connection name
  140.      *
  141.      * @return Doctrine\DBAL\Connection 
  142.      */
  143.     public function getConnection($name='default')
  144.     {
  145.         if (isset($this->_cache['dbal'][$name]=== true
  146.             && $this->_cache['dbal'][$nameinstanceof DBAL\Connection
  147.         {
  148.             return $this->_cache['dbal'][$name];
  149.         }
  150.  
  151.         $config $this->dbal[$name];
  152.         $conn   DBAL\DriverManager::getConnection(
  153.             $config,
  154.             $this->_getDBALConfiguration($config),
  155.             $this->_getEventManager($config)
  156.         );
  157.  
  158.         $this->_cache['dbal'][$name$conn;
  159.  
  160.         return $conn;
  161.  
  162.     }//end getConnection()
  163.  
  164.     /**
  165.      * Returns a cache instance. Drivers can be specified by their
  166.      * fully qualified name e.g. Doctrine\Common\Cache\ArrayCache or by their
  167.      * short name e.g. ArrayCache.
  168.      *
  169.      * If driver class is a custom implementation, it must extend from
  170.      * Doctrine\Common\Cache\AbstractCache.
  171.      *
  172.      * @param sting $name the cache name
  173.      *
  174.      * @return Doctrine\Common\Cache\AbstractCache 
  175.      * @throws CException
  176.      */
  177.     public function getCache($name='default')
  178.     {
  179.         if (isset($this->_cache['cache'][$name]=== true
  180.             && $this->_cache['cache'][$nameinstanceof Cache\AbstractCache
  181.         {
  182.             return $this->_cache['cache'][$name];
  183.         }
  184.  
  185.         if (isset($this->cache[$name]=== false{
  186.             throw new \CException(
  187.                 \Yii::t(
  188.                     'wk',
  189.                     'Unknown cache configuration "{name}"',
  190.                     array('{name}' => $name)
  191.                 )
  192.             );
  193.         }
  194.  
  195.         $doctrineDrivers array(
  196.             'ApcCache'      => 'Doctrine\Common\Cache\ApcCache',
  197.             'ArrayCache'    => 'Doctrine\Common\Cache\ArrayCache',
  198.             'MemcacheCache' => 'Doctrine\Common\Cache\MemcacheCache',
  199.             'XcacheCache'   => 'Doctrine\Common\Cache\XcacheCache',
  200.         );
  201.  
  202.         $config $this->cache[$name];
  203.  
  204.         if (array_key_exists($config['driver']$doctrineDrivers=== true{
  205.             $driver new $doctrineDrivers[$config['driver']];
  206.         else if (in_array($config['driver']$doctrineDrivers=== true{
  207.             $driver new $config['driver'];
  208.         else if (isset($config['driver']=== true{
  209.             $driver new $config['driver'];
  210.             if ($driver instanceof Cache\AbstractCache === false{
  211.                 throw new \CException(
  212.                     \Yii::t(
  213.                         'wk',
  214.                         'Cache driver must inherit from AbstractCache'
  215.                     )
  216.                 );
  217.             }
  218.         }
  219.  
  220.         if (isset($driver=== false{
  221.             throw new \CException(
  222.                 \Yii::t(
  223.                     'wk',
  224.                     'Unknown cache configuration "{name}"',
  225.                     array('{name}' => $name)
  226.                 )
  227.             );
  228.         }
  229.  
  230.         if (isset($config['namespace']=== true{
  231.             $driver->setNamespace($config['namespace']);
  232.         }
  233.  
  234.         if (method_exists($driver'initialize'=== true{
  235.             $driver->initialize($config);
  236.         }
  237.  
  238.         if ($driver instanceof Cache\MemcacheCache{
  239.             $defaultServer array(
  240.                 'host'          => 'localhost',
  241.                 'port'          => 11211,
  242.                 'persistent'    => true,
  243.                 'weight'        => 1,
  244.                 'timeout'       => 1,
  245.                 'retryInterval' => 15,
  246.                 'status'        => true
  247.             );
  248.  
  249.             $memcache new \Memcache();
  250.  
  251.             if (isset($config['servers']=== true{
  252.                 foreach ($config['servers'as $server{
  253.                     $server array_replace_recursive(
  254.                         $defaultServer,
  255.                         $server
  256.                     );
  257.  
  258.                     $memcache->addServer(
  259.                         $server['host'],
  260.                         $server['port'],
  261.                         $server['persistent'],
  262.                         $server['weight'],
  263.                         $server['timeout'],
  264.                         $server['retryInterval'],
  265.                         $server['status']
  266.                     );
  267.                 }
  268.             else {
  269.                  $memcache->addServer(
  270.                      $defaultServer['host'],
  271.                      $defaultServer['port'],
  272.                      $defaultServer['persistent'],
  273.                      $defaultServer['weight'],
  274.                      $defaultServer['timeout'],
  275.                      $defaultServer['retryInterval'],
  276.                      $defaultServer['status']
  277.                  );
  278.             }//end if
  279.  
  280.             $driver->setMemcache($memcache);
  281.         }//end if
  282.  
  283.         $this->_cache['cache'][$name$driver;
  284.  
  285.         return $driver;
  286.  
  287.     }//end getCache()
  288.  
  289.     /**
  290.      * Returns an entity manager
  291.      *
  292.      * @param string $name the entity manager configuration name
  293.      *
  294.      * @return Doctrine\ORM\EntityManager 
  295.      * @throws CException
  296.      */
  297.     public function getEntityManager($name='default')
  298.     {
  299.         if (isset($this->_cache['em'][$name]=== true{
  300.             return $this->_cache['em'][$name];
  301.         }
  302.  
  303.         if (isset($this->entityManager[$name]=== false{
  304.             throw new \CException(
  305.                 \Yii::t(
  306.                     'wk',
  307.                     'Unknown entity manager configuration "{name}"',
  308.                     array('{name}' => $name)
  309.                 )
  310.             );
  311.         }
  312.  
  313.         $options $this->entityManager[$name];
  314.         $conn    $this->getConnection($options['connection']);
  315.         $config  new ORM\Configuration();
  316.  
  317.         unset($options['connection']);
  318.  
  319.         $driver $this->_getMappingDriver($options);
  320.         $config->setMetadataDriverImpl($driver);
  321.  
  322.         // set metadata cache
  323.         if (isset($options['metadataCache']=== true{
  324.             $config->setMetadataCacheImpl(
  325.                 $this->getCache($options['metadataCache'])
  326.             );
  327.             unset($options['metadataCache']);
  328.         }
  329.  
  330.         // set query cache
  331.         if (isset($options['queryCache']=== true{
  332.             $config->setQueryCacheImpl(
  333.                 $this->getCache($options['queryCache'])
  334.             );
  335.             unset($options['queryCache']);
  336.         }
  337.  
  338.         // set result cache
  339.         if (isset($options['resultCache']=== true{
  340.             $config->setResultCacheImpl(
  341.                 $this->getCache($options['resultCache'])
  342.             );
  343.             unset($options['resultCache']);
  344.         }
  345.  
  346.         $options['proxyDir'= \Yii::getPathOfAlias($options['proxyDir']);
  347.  
  348.         // loop through setters of remaining options
  349.         foreach ($options as $key => $value{
  350.             $method 'set' ucfirst($key);
  351.             if (method_exists($config$method=== true{
  352.                 $config->{$method}($value);
  353.             }
  354.         }
  355.  
  356.         $em ORM\EntityManager::create($conn$config);
  357.  
  358.         $this->_cache['em'][$name$em;
  359.  
  360.         return $em;
  361.  
  362.     }//end getEntityManager()
  363.  
  364.     /**
  365.      * Take the configuration and return a mapping driver
  366.      *
  367.      * @param array &$config the driver options
  368.      *
  369.      * @return Doctrine\ORM\Mapping\Driver\Driver 
  370.      */
  371.     private function _getMappingDriver(array $config)
  372.     {
  373.         $drivers array(
  374.             'XmlDriver'  => 'Doctrine\ORM\Mapping\Driver\XmlDriver',
  375.             'YamlDriver' => 'Doctrine\ORM\Mapping\Driver\YamlDriver',
  376.         );
  377.  
  378.         if (is_array($config['mappingPaths']=== true{
  379.             foreach ($config['mappingPaths'as $index => $path{
  380.                 $config['mappingPaths'][$index= \Yii::getPathOfAlias($path);
  381.             }
  382.         else {
  383.             $config['mappingPaths'= \Yii::getPathOfAlias($config['mappingPaths']);
  384.         }
  385.  
  386.         // set default annotation driver
  387.         if (array_key_exists($config['mappingDriver']$drivers=== false
  388.             || $config['mappingDriver'=== 'AnnotationDriver'
  389.         {
  390.             $reader new AnnotationReader();
  391.             $reader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
  392.             $driver new AnnotationDriver($reader$config['mappingPaths']);
  393.             unset($config['mappingDriver']);
  394.             unset($config['mappingPaths']);
  395.             return $driver;
  396.         }
  397.  
  398.         $mappingClass $drivers[$config['mappingDriver']];
  399.         $driver       new $mappingClass($config['mappingPaths']);
  400.  
  401.         if (isset($config['mappingDriverOptions']=== true{
  402.             foreach ($config['mappingDriverOptions'as $key => $value{
  403.                 $method 'set' ucfirst($key);
  404.                 if (method_exists($driver$method=== true{
  405.                     $driver->{$method}($value);
  406.                 }
  407.             }
  408.  
  409.             unset($config['mappingDriverOptions']);
  410.         }
  411.  
  412.         unset($config['mappingDriver']);
  413.         unset($config['mappingDriverPaths']);
  414.  
  415.         return $driver;
  416.  
  417.     }//end _getMappingDriver()
  418.  
  419.     /**
  420.      * Get an event manager configuration
  421.      *
  422.      * @param array $config the configuration
  423.      *
  424.      * @return Doctrine\Common\EventManager|null
  425.      */
  426.     private function _getEventManager(array $config=array())
  427.     {
  428.         if (isset($config['eventManagerClass']=== false{
  429.             return null;
  430.         }
  431.  
  432.         if (isset($this->_cache['eventManager']=== false{
  433.             $eventManagerClass $config['eventManagerClass'];
  434.             $this->_cache['eventManager'new $eventManagerClass();
  435.         }
  436.  
  437.         if (isset($config['eventSubscribers']=== true{
  438.             foreach ($config['eventSubscribers'as $subscriber{
  439.                 $sub new $subscriber();
  440.                 $this->_cache['eventManager']->addEventSubscriber($sub);
  441.             }
  442.         }
  443.  
  444.         return $this->_cache['eventManager'];
  445.  
  446.     }//end _getEventManager()
  447.  
  448.     /**
  449.      * Get a DBAL configuration
  450.      *
  451.      * @param array $config the configuration
  452.      *
  453.      * @return Doctrine\DBAL\Configuration|null
  454.      */
  455.     private function _getDBALConfiguration(array $config=array())
  456.     {
  457.         if (array_key_exists('configurationClass'$config=== false{
  458.             return;
  459.         }
  460.  
  461.         $configClass   $config['configurationClass'];
  462.         $configuration new $configClass();
  463.  
  464.         if (empty($config['sqlLoggerClass']=== false{
  465.             $sqlLoggerClass $config['sqlLoggerClass'];
  466.             $loggerClass    new $sqlLoggerClass();
  467.             $configuration->setSQLLogger($loggerClass);
  468.         }
  469.  
  470.         return $configuration;
  471.  
  472.     }//end _getDBALConfiguration()
  473.  
  474. }//end class

Documentation generated on Fri, 13 May 2011 14:16:00 +0100 by phpDocumentor 1.4.3