1

我在 Symfony2 中有以下服务定义

app.service_1:
   class: Symfony\Component\Lock\Store\RedisStore
   arguments:
       - '@snc_redis.default_cache'

app.service_2:
    class: Symfony\Component\Lock\Store\RedisStore
    arguments:
        - '@snc_redis.scheduler_cache'

现在我计划升级到 Symnfony4,我需要将类路径作为服务名称

Symfony\Component\Lock\Store\RedisStore
   arguments:
       - '@snc_redis.default_cache'

Symfony\Component\Lock\Store\RedisStore
    arguments:
        - '@snc_redis.scheduler_cache'

这里的问题是它具有相同的名称,因为我们使用相同的类路径?我该如何解决?我可以使用具有不同参数的别名吗?

4

2 回答 2

1

您无需更改定义。

当您需要从同一个类创建多个服务时,使用 FQCN 作为标识符将不起作用。建议使用完全限定的类名,这是一种很好的做法,但这不是强制性的。大多数情况下它都很实用,因为您可以省略class参数,并且您不需要为每个服务选择名称。

您的原始定义与 Symfony 4(或 5)完全兼容:

app.service_1:
   class: Symfony\Component\Lock\Store\RedisStore
   arguments:
       - '@snc_redis.default_cache'

app.service_2:
    class: Symfony\Component\Lock\Store\RedisStore
    arguments:
        - '@snc_redis.scheduler_cache'

我只是建议使用比service_1and更具描述性的标识符service_2

于 2021-03-10T10:56:28.923 回答
-1

另一种方法是使用别名,如文档中的解释

services:
  Symfony\Component\Lock\Store\RedisStore:
    public: false
    arguments:
      - '@snc_redis.default_cache'

  app.service_1:
    alias: Symfony\Component\Lock\Store\RedisStore
    public: true

  Symfony\Component\Lock\Store\RedisStore:
    arguments:
      - '@snc_redis.scheduler_cache'
  app.service_2:
    alias: Symfony\Component\Lock\Store\RedisStore
    public: true

你也可以使用bindandautowire: true作为你的论点。但是您在 services.yml 中的变量必须与在您的服务的构造函数中声明的变量相同。看起来像这样:

services:
  # default configuration for services in *this* file
  _defaults:
    autowire: true      
    autoconfigure: true
    bind:
      $defaultCache: '@snc_redis.default_cache'
      $schedulerCache: '@snc_redis.scheduler_cache'

    Symfony\Component\Lock\Store\RedisStore:
      public: false

(或仅在您的服务声明中使用绑定)。

PS:在你的例子中小心,你错过:了课程路径:)

于 2021-03-10T15:58:18.860 回答