【发布时间】:2016-04-23 22:17:58
【问题描述】:
嗨,关于依赖注入的快速问题
我正在使用 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);
}
}
即使我扩展类然后尝试构造 parent no joy,显然我可以注入 Doctrine manager 进入 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;
}
}
对于 symfony 组件,我已经定义了类似的服务
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"
【问题讨论】:
标签: php dependency-injection symfony