2016-08-13 47 views
1
class CustomSawException extends Exception implements ServiceLocatorAwareInterface, SawExceptionInterface 
{ 
    protected $serviceLocator; 

    public function test(){ 
     $this->serviceLocator->get('SomeThing'); 
    } 

    /** 
    * Set service locator 
    * 
    * @param ServiceLocatorInterface $serviceLocator 
    */ 
    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) 
    { 
     $this->serviceLocator = $serviceLocator; 
    } 

    /** 
    * Get service locator 
    * 
    * @return ServiceLocatorInterface 
    */ 
    public function getServiceLocator() 
    { 
     return $this->serviceLocator; 
    } 

時引發的,這是唯一的例外:獲取對空服務定位爲null

()調用我無法弄清楚,爲什麼它拋出異常? ServiceLocatorAwareInterface應該注射了ServiceLocator

+1

「...是爲此引發的異常」...何時?你打這個班怎麼樣?服務定位器只能在服務管理器正在實例化類時注入。 –

回答

1

我認爲這是因爲你沒有使用ServiceManager實例化這個服務。

ServiceLocatorAwareInterface僅在通過ServiceManager調用此服務時纔有效。

如果使用

new CustomSawException(); 

中的ServiceManager之外,那麼AwareInterface不能設置服務定位。

如果服務沒有依賴關係,或者在另一種情況下是工廠,則應該聲明此服務爲可調用服務。