Symfony从扩展类设置依赖注入

时间:2018-06-09 11:13:05

标签: php symfony dependency-injection doctrine

我想像这样注入抽象类:

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);
    }

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

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);
    }

2 个答案:

答案 0 :(得分:1)

你试过这个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

答案 1 :(得分:0)

按照音符指示

  

如果您的文件中有_defaults部分,则所有子服务都是   需要显式覆盖这些值以避免歧义。您   会看到关于此的明确错误消息。

@brucie-alpha链接引用的

,我可以管理父服务的公共依赖项。这个解决方案对我有用,因为我在services.yaml文件中使用 _defaults 部分

App\Infrastructure\Persistence\BaseDoctrineRepository:
    abstract: true
    public: false
    autowire: false
    autoconfigure: false
    arguments:
      $eventStore: '@broadway.event_store'
      $registry: '@doctrine'
      $eventBus: '@broadway.event_handling.event_bus'

App\Infrastructure\Persistence\User\DoctrineUserRepository:
    parent: 'App\Infrastructure\Persistence\BaseDoctrineRepository'
    public: true
    autowire: false
    autoconfigure: false