Bundle 中的 Symfony 4 _instanceof services.yaml

Symfony 4 _instanceof in Bundle's services.yaml

我有一个有接口的包 Optimax\HealthCheckBundle\Service\HealthInterface 我需要为实现此接口的所有服务设置标签。我使用以下指令执行此操作:

_instanceof:
  Optimax\HealthCheckBundle\Service\HealthInterface:
    tags: ['health.service']

当我将此指令放入 config/services.yaml 时它工作正常。但是,如果我将此代码放入我的包的配置中(通过作曲家需要)vendor/optimax/health-check/src/Resources/config/services.yaml 它不起作用。我不希望每次在我需要这个包到一个新项目时将这个指令复制粘贴到 services.yaml 中。

如何将此指令移动到我的 Bundle 目录中的 services.yaml 中,或者至少移动到项目的 config/packages 文件夹中的另一个文件中?

您是否试过在您的 Bundle 扩展中使用此接口自动标记所有服务,如下所示:

$container->registerForAutoconfiguration(CustomInterface::class)
     ->addTag('app.custom_tag')
;

摘自 Symfony 文档: https://symfony.com/doc/current/service_container/tags.html

为其他人扩展此问题。

_instanceof functions identically to the _defaults定义。因为 _instanceof 定义仅适用于使用它的文件。

这可以防止第三方包定义影响您的整个应用程序,其定义如下:

_defaults: 
    public: true
    autowire: false

_instanceof:
    Psr\Log\LoggerAwareInterface:
        - method: setLogger
          arguments:
              - '@custom_logger'
        tags:
            - { name: monologer.log, channel: 'custom_channel' }

因此,如果您尝试使用 _instanceof 标记的服务未在同一 services.yml 文件中声明,则不会添加该标记。

要标记在整个应用程序中实现接口的服务,您需要使用