首页 > 解决方案 > 使用默认值覆盖父 symfony 服务的参数

问题描述

世界!

我正在尝试使用 parent 属性覆盖 Symfony DI 中基本 PHP 类的一些参数,但我不能。

Basic 类有很多参数,它们的默认值在抽象 symfony 服务中描述。YAML:

    App\BasicClass:
      class: App\BasicClass
      public: false
      abstract: true
      arguments:
        - '@App\Finder\DefaultFinder' #App\Finder\FinderInterface
        - '@App\Builder\DefaultBuilder' #App\Builder\BuilderInterface
        - ...
        - ...
        - !php/const App\Enum\CountryCode::COUNTRY_UNDEFINED

在我的子班中,我只需要覆盖其中的 3 个。我试过的:

    app.myChildClass:
      parent: App\BasicClass
      bind:
        App\Finder\FinderInterface: '@App\Finder\CustomFinder'
        App\Builder\BuilderInterface: '@App\Finder\CustomBuilder'

在这种情况下,我收到一个错误:

为服务 \"app.myChildClass\" 的类型为 \"App\\Finder\\FinderInterface\" 的参数配置了绑定,但未找到对应的参数

即使接口的名称空间是正确的。如果我指定参数名称(因为它在构造函数中)而不是命名空间,则会出现相同的错误: $finder: @App\Finder\CustomFinder

仅当我使用“arguments”属性而不是“bind”的参数名称时,覆盖才有效,如下所示:

app.myChildClass:
  parent: App\BasicClass
  arguments:
    $finder: '@App\Finder\CustomFinder'
    $builder: '@App\Finder\CustomBuilder'

但是我遇到的第二个问题是我希望通过 _defaults 部分绑定一个参数(一个常量):

    _defaults:
      bind:
        $country: !php/const App\Enum\CountryCode::COUNTRY_UKR

    app.myChildClass:
      parent: App\BasicClass
      arguments:
        $finder: '@App\Finder\CustomFinder'
        $builder: '@App\Finder\CustomBuilder'

但是 id 可能由于使用“参数”而不是“绑定”而没有跳入我的服务:(所以我很困惑,这里有没有机会简化这个覆盖或者我必须复制该行

$country: !php/const App\Enum\CountryCode::COUNTRY_UKR

在我的儿童服务定义中?

谢谢!

标签: phpsymfony

解决方案


推荐阅读