喜約依賴注入的簡單問題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"
感謝Wouter,所以如果你通過構造函數傳遞一些東西,你可以訪問正在傳遞的類的所有東西,包括它構造的東西嗎? – hounded
是的,你很可靠。 –