将动态变量传递给服务构造函数 [英] Passing dynamic variables to a service constructor
本文介绍了将动态变量传递给服务构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Symfony2 中有一个如下所示的服务:
I have a service in Symfony2 that looks like:
services:
MyCustomService:
class: MyClass
arguments: //Arguments aren't static, but dynamic based on application logic.
是否可以将动态变量传递给服务的构造函数?
Is it possible to pass dynamic variables to a service's constructor?
控制器的 $this->get('MyCustomService');
有什么我遗漏的吗?
推荐答案
如果由于某种原因,您无法在实例化后配置服务(即 带有配置器).将责任委托给工厂怎么样?它将让您使用动态参数"实例化服务.
If, for whatever reason, you are unable to configure the service after instantiation (i.e., with a configurator). What about delegating that responsibility to a factory? It will let you instantiate services with "dynamic arguments".
services:
MyCustomServiceFactory:
class: MyClassFactory
arguments: [ @dynamicService, %time_prefix% ]
MyCustomService:
class: MyClass
factory_service: MyCustomServiceFactory
factory_method: get
您的工厂想要这样的东西:
Your factory would like something like this:
class MyClassFactory
{
private $dynamicService;
private $timePrefix;
public function __construct(MyDynamicService $dynamicService, $timePrefix)
{
$this->dynamicService = $dynamicService;
$this->timePrefix = $timePrefix;
}
public function get()
{
// Dynamic arguments based on application logic.
$dynamicArg1 = $this->dynamicService->getArg()
$dynamicArg2 = $this->timePrefix . time();
return new MyClass($dynamicArg1, $dynamicArg2);
}
}
这篇关于将动态变量传递给服务构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文