Dependency injection 无法使用DI在Module::onBootstrap中获取条令\ORM\EntityManger

Dependency injection 无法使用DI在Module::onBootstrap中获取条令\ORM\EntityManger,dependency-injection,zend-framework2,Dependency Injection,Zend Framework2,我遇到一些问题,我需要初始化一些RouteGuard: RouteGuard.php namespace Acl\Guard; use Zend\ServiceManager\ServiceManagerAwareInterface; use Zend\ServiceManager\ServiceManagerAwareTrait; class RouteGuard implements ServiceManagerAwareInterface { use ServiceLocator

我遇到一些问题,我需要初始化一些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');
    }

}
名称空间Acl\Guard;
类路由守卫{
公共函数构造(EntityManager$em)
{
}
}
Module.php

。。。。。。。。。
类模块{
引导上的公共函数(MvcEvent$e)
{
$sm=$e->getApplication()->getServiceManager();
$eventManager=$e->getApplication()->getEventManager();
$eventManager->attach($sm->get('di')->get('Acl\Guard\RouteGuard'));
}
.....
我得到一个例外:

  • 致命错误:第767行的[projectDir]/vendor/zendframework/zendframework/library/Zend/Di/Di.php中出现未捕获的异常“Zend\Di\exception\RuntimeException”,消息为“Doctrine\ORM\EntityManager.”的“NULL”类型的实例化器无效
  • Zend\Di\Exception\RuntimeException:在第298行的[projectDir]/vendor/zendframework/zendframework/library/Zend/Di/Di.php中,“条令\ORM\EntityManager”的类型为“NULL”的实例化器无效
  • Zend\Di\Exception\MissingPropertyException:在第767行的[projectDir]/vendor/zendframework/zendframework/library/Zend/Di/Di.php中缺少参数entityManager for Acl\Service\AclService::u构造的实例/对象
  • 我知道我试图获得(条令\ORM\EntityManager)DI试图创建新实例,但由于EntityManager有一个受保护的构造函数而出错。我知道EntityManager应该使用静态方法::create实例化,但我看到DoctrineORMModule已经有一个配置为Doctrine的Doctrine\ORM\EntityManager实例,那么我如何才能在中获得此实例用DI引导


    提前感谢。

    我认为在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()来检索实体管理器。

    这不好,因为这是ServiceLocator方式,不适合我的任务,我需要解决涉及DI构造函数注入的问题。但谢谢您的回答。