Jeśli jesteś właścicielem tej strony, możesz wyłączyć reklamę poniżej zmieniając pakiet na PRO lub VIP w panelu naszego hostingu już od 4zł!

Access entity manager in Zend Framework 2 unit tests

Access entity manager in Zend Framework 2 unit tests

In order to access the entity manager in your unit tests you will have to make your PHPUnit bootstrap file a little bit more complex. You will need to access the entity manager if you are using Doctrine module together with Zend Framework 2.

Here is what I have done:

  1. <?php
  2.  
  3. use ZendServiceManagerServiceManager,
  4.     ZendMvcServiceServiceManagerConfig;
  5.  
  6. class Bootstrap
  7. {
  8.     static public $config;
  9.     static public $sm;
  10.     static public $em;
  11.  
  12.     static public function go()
  13.     {
  14.         chdir(dirname(__DIR__));
  15.         include __DIR__ . '/../init_autoloader.php';
  16.         self::$config = include 'config/application.config.php';
  17.         ZendMvcApplication::init(self::$config);
  18.         self::$sm = self::getServiceManager(self::$config);
  19.         self::$em = self::getEntityManager(self::$sm);
  20.     }
  21.  
  22.     static public function getServiceManager($config)
  23.     {
  24.         $serviceManager = new ServiceManager(new ServiceManagerConfig);
  25.         $serviceManager->setService('ApplicationConfig', $config);
  26.         $serviceManager->get('ModuleManager')->loadModules();
  27.         return $serviceManager;
  28.     }
  29.  
  30.     static public function getEntityManager($serviceManager)
  31.     {
  32.         return $serviceManager->get('doctrine.entitymanager.orm_default');
  33.     }
  34. }
  35.  
  36. Bootstrap::go();

And then in your unit tests you can access the entity manager simply by:

  1. Bootstrap:$em

That was quite easy actually.

Source: http://blog.richardknop.com/2012/09/access-entity-manager-in-zend-framework-2-unit-tests/

<!–
var d = new Date();
r = escape(d.getTime()*Math.random());
document.writeln('’);
//–>

Posted Wrzesień 27th, 2012 in Zend and PHP.

Leave a response: