【问题标题】:PHP Dependency injection and InheritancePHP 依赖注入和继承
【发布时间】: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


    【解决方案1】:

    依赖注入只是将对象传递给构造函数(或设置方法)的过程。依赖注入容器(或服务容器)只不过是一个帮助器,用于将对象的正确实例注入到构造函数中。

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

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

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

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

    tl;dr:您在问题中显示的代码(除了奇怪的扩展示例)运行良好。

    【讨论】:

    • 谢谢 Wouter,所以如果你通过构造函数传递一些东西,你可以访问正在传递的类中的所有内容,包括它构造的任何内容?
    • 是的,你是对的。
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2011-12-24
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    相关资源
    最近更新 更多