首页 > 解决方案 > 如何使用类常量作为绑定参数服务的标签?

问题描述

我在我的配置中标记了一组实现相同接口的服务:

// services.yml
services:
  _instanceof:
     App\SomeInterface:
       tags: [ !php/const App\SomeInterface::TAG ]

(其中的值为 App\SomeInterface::TAGvery_unique_identifier

我想重用这个值来绑定这个参数,如下所示:

// services.yaml
 services:
  _defaults:
    autowire: true      
    autoconfigure: true 
    public: false
    bind:
      $fooStrategies: !tagged !php/const App\SomeInterface::TAG 

但是当我这样做时,我得到一个空的RewindableGenerator.

相反,我可以这样做,使用常量的文字值:

bind:
      $fooStrategies: !tagged 'very_unique_identifier'

...并且它按预期工作,并且RewindableGenerator内部具有所有必要的服务。

如何在两个地方都使用 PHP 常量,这样我就不必在不同的地方重复值?显然,这不是什么大不了的事,但如果可能的话,我想避免它。

标签: phpsymfonysymfony4symfony-dependency-injection

解决方案


您应该能够使用该值配置参数, !php/const App\SomeInterface::TAG然后使用 service.yml 中的参数名称。

parameters.yml

parameters:
    interfaceTag: !php/const App\SomeInterface::TAG

接着

services.yml

services:
  _defaults:
     autowire: true      
     autoconfigure: true 
     public: false
     bind:
       $fooStrategies: !tagged '%interfaceTag%'

推荐阅读