如何解决在 Symfony4 中使用 Symfony2 服务定义,为同一个类提供多个服务
我在 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'
这里的问题是它具有相同的名称,因为我们使用相同的类路径?我该如何解决?我可以使用具有不同参数的别名吗?
解决方法
您不需要更改定义。
当您需要从同一类创建多个服务时,使用 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_1
和 service_2
更具描述性的标识符。
另一种方法是在 documentation
中使用类似解释的别名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
您还可以使用 bind
和 autowire: 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
(或仅在您的服务声明中使用 bind)。
PS:在你的例子中要小心,你错过了课程路径后的 :
:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。