ZF2 how to get entity Manager from outside of controller

蹲街弑〆低调 提交于 2019-12-31 17:56:06

问题


we can access entity manager within controller using $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

but how can we access entity manager singleton instance in rest of the project in Zendframework 2.


回答1:


The 'right' way to do it is use a factory to inject the entity manager into any classes that need it. Classes, other than factories, shouldn't really be aware of the ServiceLocator. So, your module config would look like this:

 'controllers' => array(
     'factories' => array(
          'mycontroller' => 'My\Namespace\MyControllerFactory'
     )
 )

Then your factory class would look something like this:

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MyControllerFactory implements FactoryInterface
{

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $serviceLocator = $serviceLocator->getServiceLocator();

        $myController = new MyController;
        $myController->setEntityManager(
            $serviceLocator->get('doctrine.entitymanager.orm_default')
        );

        return $myController;
    }
}

Follow the same pattern for any other classes that need to consume the entity manager.

If, you have lots and lots of classes that consume the entity manager, you might want to consider adding your own Initalizer to the SerivceManager that will inject the entity manager without the need for a factory.



来源:https://stackoverflow.com/questions/11866504/zf2-how-to-get-entity-manager-from-outside-of-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!