php - Symfony 设置扩展类的依赖注入(inject)

标签 php symfony dependency-injection doctrine

我想像这样注入(inject)抽象类:

services:
    App\Infrastructure\Persistence\BaseDoctrineRepository:
        arguments:
          $eventStore: '@broadway.event_store'
          $registry: '@doctrine'
          $eventBus: '@broadway.event_handling.event_bus'

,但如果这样做的话我会得到:

Cannot autowire service "App\Infrastructure\Persistence\User\DoctrineUserRepository": argument "$eventStore" of method "__construct()" references interface "Broadway\EventStore\EventStore" but no such service exists. You should maybe alias this interface to one of these existing services: "broadway.event_store.dbal", "broadway.event_store.in_memory". 

所以我需要为每个存储库复制这样的代码,我想避免它。

services:
    App\Infrastructure\Persistence\User\DoctrineUserRepository:
        arguments:
          $eventStore: '@broadway.event_store'
          $registry: '@doctrine'
          $eventBus: '@broadway.event_handling.event_bus'

抽象类:

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;

abstract class BaseDoctrineRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry, EventStore $eventStore, EventBus $eventBus)
    {
        $this->eventStore = $eventStore;
        $this->eventBus = $eventBus;
        parent::__construct($registry, static::REPOSITORY_CLASS);
    }

从抽象中扩展的类(我想避免构造函数):

class DoctrineUserRepository extends BaseDoctrineRepository implements UserRepository
{
    const REPOSITORY_CLASS = User::class;

    public function __construct(ManagerRegistry $registry, EventStore $eventStore, EventBus $eventBus)
    {
        parent::__construct($registry, $eventStore, $eventBus);
    }

最佳答案

你试过这个吗https://symfony.com/doc/current/service_container/parent_services.html

基本上就是这样

services:
    App\Infrastructure\Persistence\BaseDoctrineRepository:
            abstract: true
            arguments:
              $eventStore: '@broadway.event_store'
              $registry: '@doctrine'
              $eventBus: '@broadway.event_handling.event_bus'
    App\Infrastructure\Persistence\User\DoctrineUserRepository:
        parent: App\Infrastructure\Persistence\BaseDoctrineRepository

关于php - Symfony 设置扩展类的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50773651/

相关文章:

c# - 需要帮助了解 Ninject 如何将 Nhibernate SessionFactory 实例放入 UnitOfWork 中?

php - 使用 cURL 发出的 SSL 请求在进程 fork 后失败

php - 如果用户输入数据失败,如何确保MySQL中的列不显示默认的 "0"?

php - 我可以使用 PHP 从同一个 MYSQL 表中的另外两个单元格更新一个单元格吗

php - Symfony2 项目中基于 Doctrine 的认证机制

asp.net-mvc - 如何将 Ninject 与 ASP.NET Web API 一起使用?

php - 如何在 Laravel 中正确向 Controller 发送 PUT/UPDATE 请求

html - 扩展模板不适用于 FOSUserBundle 电子邮件。交响乐2

php - 尝试清除我的数据库时出现语法错误

Java从一个war文件注入(inject)到另一个war文件