ZF2如何从控制器外部获取实体管理器

Dev*_*per 6 zend-framework2

我们可以使用控制器访问实体管理器 $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

但是我们怎样才能在Zendframework 2中的项目的其余部分访问实体管理器单例实例.

sup*_*bie 12

"正确"的方法是使用工厂将实体管理器注入任何需要它的类.除工厂之外的类不应该真正了解ServiceLocator.所以,你的模块配置看起来像这样:

 'controllers' => array(
     'factories' => array(
          'mycontroller' => 'My\Namespace\MyControllerFactory'
     )
 )
Run Code Online (Sandbox Code Playgroud)

然后你的工厂类看起来像这样:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于需要使用实体管理器的任何其他类,遵循相同的模式.

如果您有许多使用实体管理器的类,您可能需要考虑将自己的Initalizer添加到SerivceManager,它将注入实体管理器而无需工厂.