无法使用DI在Module :: in Bootstrap中获取Doctrine \ ORM \ EntityManager

时间:2013-06-26 11:51:28

标签: dependency-injection zend-framework2

我遇到了一些麻烦,我需要初始化一些RouteGuard:

RouteGuard.php

namespace Acl\Guard;

class RouteGuard {
    public function __construct(EntityManager $em)
    {

    }
}

Module.php

.........
class Module {
   public function onBootstrap(MvcEvent $e)
   {
      $sm = $e->getApplication()->getServiceManager();
      $eventManager = $e->getApplication()->getEventManager();
      $eventManager->attach($sm->get('di')->get('Acl\Guard\RouteGuard'));
   }
.....

我得到了这个例外:

  1. 致命错误:未捕获的异常'Zend \ Di \ Exception \ RuntimeException',并显示消息'Doctrine \ ORM \ EntityManager'的类型为“NULL”的无效实例化器。在第767行的[projectDir] /vendor/zendframework/zendframework/library/Zend/Di/Di.php
  2. Zend \ Di \ Exception \ RuntimeException:“Doctrine \ ORM \ EntityManager”类型为“NULL”的实例化器无效。在第298行的[projectDir] /vendor/zendframework/zendframework/library/Zend/Di/Di.php
  3. Zend \ Di \ Exception \ MissingPropertyException:第767行的[projectDir] /vendor/zendframework/zendframework/library/Zend/Di/Di.php中的参数entityManager for Acl \ Service \ AclService :: __ construct缺少实例/对象
  4. 据我所知,我试图获取(Doctrine \ ORM \ EntityManager)并且DI尝试创建新实例并因错误而失败,因为EntityManager具有受保护的构造函数。我知道EntityManager应该使用静态方法:: create进行实例化,但是我看到DoctrineORMModule已经有一个Doctrine \ ORM \ EntityManager实例,并且配置了Doctrine,那么我怎样才能在带有DI的Bootstrap中获得这个实例?

    提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为在RouteGuard类中获取实体管理器的最佳方法是实现ServiceLocatorAwareInterface,然后始终从服务定位器中检索RouteGuard类。

RouteGuard.php

namespace Acl\Guard;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManagerAwareTrait;

class RouteGuard implements ServiceManagerAwareInterface {
    use ServiceLocatorAwareTrait;

    public function __construct()
    {

    }

    public function getEntityManager()
    {
        return $this->getServiceManager()->get('Doctrine\ORM\EntityManager');
    }

}

然后在RouteGuard中,您可以调用$ this-> getEntityManager()来检索实体管理器。