PHP依赖注入和继承

PHP依赖注入和继承,php,dependency-injection,symfony,Php,Dependency Injection,Symfony,嗨,关于依赖注入的快速问题 我正在使用symfony 3,并且正在与DI达成协议 说我有课 use Doctrine\ORM\EntityManagerInterface; class CommonRepository { /** * @var EntityManagerInterface */ protected $em; /** * DoctrineUserRepository constructor. * @param Entit

嗨,关于依赖注入的快速问题

我正在使用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的新类,我注入了上面的类,这是否意味着我可以访问注入的项目注入的项目(很明显,他在《盗梦空间》结束时是在做梦)

即使我扩展了这个类,然后尝试构建ParentNoJoy,很明显我也可以注入条令管理器 在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"           

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

话虽如此,很明显依赖注入不会以任何方式影响PHP(顺便说一句,Symfony中没有任何东西会影响PHP,它只是普通的PHP东西)

因此,继承的工作原理与处理一些普通PHP对象的工作原理一样(这是一个奇怪的比较,因为它们已经是普通PHP对象)

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

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


tl;dr:您在问题中显示的代码(除了古怪的extence示例)工作得非常好。

谢谢Wouter,因此如果您通过构造函数传递了某些内容,您可以访问正在传递的类中的所有内容,包括它构造的任何内容?是的,您是正确的。
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"