Reputation: 125
Symfony 2.8
Having a service factory, I want to pass a simple 'string' argument when call/invoke/get (however you say it) the service.
<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>
And I don't know how to set that string as a parameter.
$this->getContainer()->get('reports')->setParameter('optional', 'string_to_pass');
Service factory works, but I need to pass a parameter from controller or command.
Upvotes: 0
Views: 450
Reputation: 333
You cannot set a parameter to a service you got from the service container. It have been instantiated already. Factory service in Symfony configuration will not help you in this case too.
You can use Prototype pattern for example: get your "not configured" service from a container, clone and configure it:
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>
Upvotes: 1