Symfony 2.8
有了服务工厂,我想在调用/invoke/get(无论你怎么说)服务时传递一个简单的'string‘参数。
<services>
<service id="service.builder_factory" class="Domain\Bundle\Services\ServiceBuilder">
<argument name="optional" type="string"/>
<argument type="service" id="request_stack"/>
<argument type="service" id="event_dispatcher"/>
<argument type="service" id="doctrine.orm.entity_manager"/>
<argument key="dir">%kernel.logs_dir%</argument>
</service>
<service id="reports" class="Domain\Bundle\Services\ReportsService">
<factory service="service.builder_factory" method="__factoryMethod"/>
<tag name="service.builder"/>
</service>
</services>我不知道如何将该字符串设置为参数。
$this->getContainer()->get('reports')->setParameter('optional', 'string_to_pass');服务工厂可以工作,但我需要从控制器或命令传递一个参数。
发布于 2020-07-11 03:35:58
您不能为从服务容器获取的服务设置参数。它已经被实例化了。在这种情况下,Symfony配置中的工厂服务也不会对您有所帮助。
例如,您可以使用Prototype模式:从容器中获取“未配置”的服务,克隆并配置它:
class MyService {
private $reportPrototype;
public function __construct(Report $reportPrototype) // your 'report' service
{
$this->reportPrototype = $reportPrototype;
}
public function someMethod() {
$report = $this->getReport('optional');
}
protected function getReport(string $optional)
{
$result = clone $this->reportPrototype;
$result->setOptional($optional); // configure your service
return $result;
}
}services.xml
<services>
<service id="reports" class="Domain\Bundle\Services\ReportsService">
<argument type="service" id="request_stack"/>
<argument type="service" id="event_dispatcher"/>
<argument type="service" id="doctrine.orm.entity_manager"/>
<argument key="dir">%kernel.logs_dir%</argument>
</service>
<service id="my_service" class="MyService">
<argument type="service" id="reports"/>
</service>
</services>https://stackoverflow.com/questions/62839960
复制相似问题