2016-04-23 119 views
2

喜約依賴注入的簡單問題PHP依賴注入和繼承

我使用symfony的3和我來到條款與DI

說我有一類

use Doctrine\ORM\EntityManagerInterface; 

class CommonRepository 
{ 
    /** 
    * @var EntityManagerInterface 
    */ 
    protected $em; 

    /** 
    * DoctrineUserRepository constructor. 
    * @param EntityManagerInterface $em 
    */ 
    public function __construct(EntityManagerInterface $em) 
    { 
     $this->em = $em; 
    } 
    public function getEntityManager() 
    { 
     return $this->em; 
    } 
} 

現在一個叫做UserRepository的新類,我注入了上面的類,這是否意味着我可以訪問注入項目注入的項目(顯然他在開始的時候是在做夢)?

class UserRepository 
{ 
    /** 
    * @var CommonDoctrineRepository 
    */ 
    private $commonRepository; 

    /** 
    * @var \Doctrine\ORM\EntityManagerInterface 
    */ 
    private $em; 

    /** 
    * DoctrineUserRepository constructor. 
    * @param CommonRepository $CommonRepository 
    */ 
    public function __construct(CommonRepository $CommonRepository) 
    { 
     $this->commonRepository = $commonRepository; 
     $this->em = $this->commonRepository->getEntityManager(); 
    } 
    public function find($id) 
    { 
     //does not seem to work 
     //return $em->find($id); 
     //nor does 
     //return $this->em->find($id); 
    } 
} 

即使我擴展類,然後試圖建立無父的喜悅,顯然我可以注入主義經理 到UserRepository,我只是試圖繞過DI一些理解和繼承

class UserRepository extends CommonRepository 
{ 
    /** 
    * @var CommonDoctrineRepository 
    */ 
    private $commonRepository; 

    /** 
    * @var \Doctrine\ORM\EntityManagerInterface 
    */ 
    private $em; 

    public function __construct(CommonDoctrineRepository $commonRepository, $em) 
    { 
     parent::__construct($em); 
     $this->commonRepository = $commonRepository; 
    } 
} 

因爲我喜歡

app.repository.common_repository: 
    class: AppBundle\Repository\Doctrine\CommonRepository 
    arguments: 
     - "@doctrine.orm.entity_manager" 

app.repository.user_repository: 
    class: AppBundle\Repository\Doctrine\UserRepository 
    arguments: 
     - "@app.repository.common_repository"   

回答

3

依賴注入定義的服務symfony的部件是傳遞對象到的只是過程構造函數(或setter方法)。依賴注入容器(或服務容器)只不過是將正確的對象實例注入構造函數的助手。這說明,很顯然,依賴注入不會以任何方式影響PHP(順便說一句,Symfony沒有做什麼,它只是簡單的PHP東西)。

因此,繼承的工作方式與一些普通的PHP對象一樣(這是一個奇怪的比較,因爲它們已經是普通的PHP對象)。

這意味着如果CommonRepository#getEntityManager()是公開的且CommonRepository已正確實例化,則此方法應返回傳遞給其構造函數的實體管理器。

這同樣適用於UserRepository:如果保存通過CommonRepository#getEntityManager()實例在$em財產,所有方法都可以使用此$em屬性訪問實體管理器。這意味着做$this->em->find(...)應該完美的工作($em->find(...)不應該,因爲沒有$em變量)。

tl; dr:你在你的問題中顯示的代碼(除了怪異的extence例子)完美的作品。

+1

感謝Wouter,所以如果你通過構造函數傳遞一些東西,你可以訪問正在傳遞的類的所有東西,包括它構造的東西嗎? – hounded

+0

是的,你很可靠。 –