我遇到了一些麻烦,我需要初始化一些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'));
}
.....
我得到了这个例外:
据我所知,我试图获取(Doctrine \ ORM \ EntityManager)并且DI尝试创建新实例并因错误而失败,因为EntityManager具有受保护的构造函数。我知道EntityManager应该使用静态方法:: create进行实例化,但是我看到DoctrineORMModule已经有一个Doctrine \ ORM \ EntityManager实例,并且配置了Doctrine,那么我怎样才能在带有DI的Bootstrap中获得这个实例?
提前谢谢。
答案 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()来检索实体管理器。