2013-06-26 25 views
2

我有一些麻煩,我需要初始化一些RouteGuard:無法獲取學說 ORM EntityManger在模塊:: onBootstrap與DI

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. 致命錯誤:對於「Doctrine \ ORM \ EntityManager」,未捕獲的異常'Zend \ Di \ Exception \ RuntimeException'帶有消息'類型爲「NULL」的無效實例化器。在[projectDir] /vendor/zendframework/zendframework/library/Zend/Di/Di.php on line 767
  2. Zend \ Di \ Exception \ RuntimeException:「Doctrine \ ORM \ EntityManager」類型爲「NULL」的無效實例化器。在[projectDir] /vendor/zendframework/zendframework/library/Zend/Di/Di.php上線298
  3. Zend \ Di \ Exception \ MissingPropertyException:缺少Acl \ Service \ AclService :: __參數entityManager的實例/對象在[PROJECTDIR]上線767

/vendor/zendframework/zendframework/library/Zend/Di/Di.php我明白,我試圖讓(學說\ ORM \的EntityManager)和DI嘗試創建新實例並由於EntityManager具有受保護的構造函數而出錯。我明白EntityManager應該用靜態方法:: create來實例化,但是我看到DoctrineORMModule已經有一個Doctrine \ ORM \ EntityManager的實例,它具有Doctrine的配置,所以我怎麼能在Bootstrap中使用DI來獲取這個實例?

謝謝,提前。

回答

0

我認爲獲得RouteGuard類中的實體管理器的最好方法是實現ServiceLocatorAwareInterface,然後始終從Service locator中檢索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可以調用$這個 - > getEntityManager()來檢索實體管理器。

+0

這是不好的,因爲它是ServiceLocator的方式,它不適合我的任務,我需要與DI構造函數注入相關的解決方案。但是,謝謝你的回答。 – SpalaX