ZF2如何从控制器外部获取实体管理器 [英] ZF2 how to get entity Manager from outside of controller

查看:22
本文介绍了ZF2如何从控制器外部获取实体管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用 $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');

但是我们如何在 Zendframework 2 的项目的其余部分访问实体管理器单例实例.

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

推荐答案

正确"的做法是使用工厂将实体管理器注入到任何需要它的类中.除了工厂,类不应该真正知道 ServiceLocator.因此,您的模块配置将如下所示:

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.

如果您有很多使用实体管理器的类,您可能需要考虑将自己的初始化器添加到 SerivceManager 中,这将在不需要工厂的情况下注入实体管理器.

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.

这篇关于ZF2如何从控制器外部获取实体管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆