PHP依赖注入和继承

时间:2016-04-23 22:17:58

标签: php dependency-injection symfony

关于依赖注入的快速问题

我正在使用 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);
    }
}

即使我扩展了课程,然后尝试构建父母没有快乐,显然我可以注入Doctrine经理 进入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"           

1 个答案:

答案 0 :(得分:3)

依赖注入只是将对象传递给构造函数(或setter方法)的过程。依赖注入容器(或服务容器)只不过是将正确的对象实例注入构造函数的帮助。

说到这一点,很明显依赖注入不会以任何方式影响PHP(顺便说一下,Symfony没有,它只是普通的PHP东西)。

因此,继承的工作方式与一些普通的PHP对象一样(这是一种奇怪的比较,因为它们已经是普通的PHP对象)。

这意味着如果CommonRepository#getEntityManager()是公共的并且CommonRepository被正确实例化,则此方法应该返回传递给其构造函数的实体管理器。

同样适用于UserRepository:如果在CommonRepository#getEntityManager()属性中保存传递的$em实例,则所有方法都可以使用此$em属性访问实体管理器。这意味着,$this->em->find(...)完全可以正常工作($em->find(...)不应该,因为没有$em变量。)

tl; dr :您在问题中显示的代码(除了奇怪的扩展示例)完美无缺。

相关问题