ZF2和EntityManager(主义)
发布时间:2020-12-13 14:05:41 所属栏目:PHP教程 来源:网络整理
导读:我有个问题.我尝试在没有控制器的情况下获得Entity-Manager,但我没有找到办法. 这时,我得到了这样的Entity-Manager: (Controller)public function getEntityManager(){ if (null === $this-_em) { $this-_em = $this-getServiceLocator()-get('DoctrineORM
我有个问题.我尝试在没有控制器的情况下获得Entity-Manager,但我没有找到办法.
这时,我得到了这样的Entity-Manager: (Controller) public function getEntityManager() { if (null === $this->_em) { $this->_em = $this->getServiceLocator()->get('DoctrineORMEntityManager'); } return $this->_em; } (Plugin) public function getEntityManager() { if($this->_em == null){ $this->_em = $this->getController()->getServiceLocator()->get('doctrine.entitymanager.orm_default'); } return $this->_em; } 你看,我总是需要一个控制器.但是,如果我需要模型中的EntityManager,我有一个问题.我可以给模型控制器,但我认为这是一个糟糕的方式. 您是否有任何想法在没有控制器的情况下获取EntityManager?
我处理Doctrine的方式是通过Services,我这样做如下:
//some Controller public function someAction() { $service = $this->getServiceLocator()->get('my_entity_service'); return new ViewModel(array( 'entities' => $service->findAll() )); } Service-> findAll()看起来像这样: public function findAll() { return $this->getEntityRepository()->findAll(); } 现在我们需要定义my_entity_service.我在Module.php中这样做 public function getServiceConfig() { return array( 'factories' => array( 'my_entity_service' => 'NamespaceFactoryMyServiceFactory' ) ); } 接下来我创建工厂(注意:这也可以通过Module.php中的匿名函数完成) <?php namespace NamespaceFactory; use ZendServiceManagerServiceLocatorInterface; use ZendServiceManagerFactoryInterface; use NamespaceModelMyModel; class MyServiceFactory implements FactoryInterface { /** * Create service * * @param ServiceLocatorInterface $serviceLocator * @return mixed */ public function createService(ServiceLocatorInterface $serviceLocator) { $myModel= new MyModel(); $myModel->setEntityManager($serviceLocator->get('DoctrineORMEntityManager')); return $myModel; } } 现在要咀嚼很多东西:D我完全明白了.这里发生的事情实际上非常简单.您可以调用ZF2的ServiceManager来为您创建模型,并将EntityManager注入其中,而不是创建模型并以某种方式进入EntityManager. 如果这仍然让你困惑,我会很乐意尝试更好地解释自己.为了进一步说明,我想了解您的用例.即:您需要EntityManager或您需要它的位置. 此代码示例超出了问题范围 只是为了给你一个关于我通过ServiceFactories表单做的事情的实例: public function createService(ServiceLocatorInterface $serviceLocator) { $form = new ReferenzwertForm(); $form->setHydrator(new DoctrineEntity($serviceLocator->get('DoctrineORMEntityManager'))) ->setObject(new Referenzwert()) ->setInputFilter(new ReferenzwertFilter()) ->setAttribute('method','post'); return $form; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读