方法返回值作为服务参数(Method return value as service parameter)

编程入门 行业动态 更新时间:2024-10-16 16:41:30
方法返回值作为服务参数(Method return value as service parameter)

我正在尝试使用method-return-value作为DI参数。 具体的用例是我有一个服务,其逻辑是计算用户国家代码,如:

$user->getCountryCode();

另一方面,我有很多依赖于国家的服务:

$foo = new Foo('UK'); $bar = new Bar('USA');

我知道我可以将用户服务注入Foo / Bar,但这会产生奇怪的依赖性,因为这些服务不需要用户只需要国家代码。

有没有办法让我按照以下方式编写服务描述:

my_services.foo: class: Foo arguments: - @user.getCountryCode

编辑:我正在使用symfony 2.4和yml配置。

I'm trying to use a method-return-value as a DI-parameter. The concrete use-case is that I have a service that has the logic of calculating a users-country-code like:

$user->getCountryCode();

On the other hand I have many services that depend on the country like:

$foo = new Foo('UK'); $bar = new Bar('USA');

I know that I can inject the User service into Foo / Bar, but that creates an odd dependency as these services don't need a user they just need the country-code.

Is there a way for me to write a service-description along the lines of:

my_services.foo: class: Foo arguments: - @user.getCountryCode

Edit: I'm using symfony 2.4 with yml configuration.

最满意答案

服务工厂方法(与所有Symfony2版本兼容)

服务定义:

# services.yml FooFactory: class: Foo\FooBundle\Service\FooFactory arguments: [@user_country_code_calc_service] FooService: class: Foo\FooBundle\Service\FooService factory_service: FooFactory factory_method: create

而你的工厂:

// FooFactory.php class FooFactory { private $countryCodeCalculator; public function __construct(UserCountryCodeCalculator $countryCodeCalculator) { $this->countryCodeCalculator = $countryCodeCalculator; } public function create() { $countryCode = $this->countryCodeCalculator->calculate(...); return new FooService($countryCode); } }

现在当你在任何服务中注入@FooFactory时,Symfony实际上会调用FooFactory::create并将该方法的结果注入其中。

Service factory method (compatible with all Symfony2 versions)

Service definitions:

# services.yml FooFactory: class: Foo\FooBundle\Service\FooFactory arguments: [@user_country_code_calc_service] FooService: class: Foo\FooBundle\Service\FooService factory_service: FooFactory factory_method: create

And your factory:

// FooFactory.php class FooFactory { private $countryCodeCalculator; public function __construct(UserCountryCodeCalculator $countryCodeCalculator) { $this->countryCodeCalculator = $countryCodeCalculator; } public function create() { $countryCode = $this->countryCodeCalculator->calculate(...); return new FooService($countryCode); } }

Now when you inject @FooFactory in any of your services, Symfony will actually call FooFactory::create and inject that method's result into it.

更多推荐

本文发布于:2023-08-04 11:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   参数   方法   Method   service

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!