Symfony AutoWire 多个服务同一个类 [英] Symfony AutoWire multiple services same class
问题描述
我正在将大型应用程序升级到 4.2
i am in the process of upgrading a large application to 4.2
和控制器内部的 $this->get(".....")
已弃用,应改用 AutoWire.
and the $this->get(".....")
from inside the controller is deprecated and one should use AutoWire instead.
我遇到了一个问题,我有 2 个服务,它们实际上来自同一个类(只是不同的构造函数参数).
i am running into the problem that i have 2 services, which are in fact from the same class (just diffrent constructor args).
services.yml
services.yml
services:
service.a:
class: Namespace\MyClass
arguments: [ "argument1" ]
service.b:
class: Namespace\MyClass
arguments: [ "argument2" ]
控制器:
public function demoAction() {
$serviceA = $this->get("service.a");
$serviceB = $this->get("service.b");
}
以及有问题的结果:
public function demoAction(MyClass $serviceA, MyClass $serviceB) {
}
我们可以使用别名来服务定义,例如:
we can use alias to service definitions like:
MyClass: '@service.a'
但我不能使用像(没有现有的)这样的虚拟/假类:
but i cannot use a virtual/fake class like (without an existing one):
MyPseudClass: '@service.b'
您如何在自动装配模式下处理此类情况?
how do you handle cases like this in autowire mode?
我可以创建从基础扩展而来的伪"类,只是为了获得不同的类名,但这感觉很奇怪.
i could create "pseudo" classes, that extend from the base, just to get different classnames, but that feels weird.
推荐答案
从 4.2 开始,您可以定义命名的自动装配别名.这应该有效:
Starting with 4.2, you can define named autowiring aliases. That should work:
services:
Namespace\MyClass $serviceA: '@service.a'
Namespace\MyClass $serviceB: '@service.b'
在 Symfony 3.4 和 4.1 中,您可以使用绑定来代替——但这不太具体,因为它没有考虑类型:
With Symfony 3.4 and 4.1, you can use bindings instead - but that's less specific as that doesn't take the type into account:
services:
_defaults:
bind:
$serviceA: '@service.a'
$serviceB: '@service.b'
这篇关于Symfony AutoWire 多个服务同一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!