How to insert a service result method as an argument to another service?

I have a FooService that retrieves some data from another configuration service.

I have this configuration service since the configuration is different depending on the request data. The configuration service has a RequestStack that is injected and builds the appropriate configuration array.

My FooService as follows:

 class Foo { private $config; /** * @param Config $config */ public function __construct(Config $config) { $this->config = $config->getData(); } } 

However, instead of introducing the service, I prefer to enter only the result of the method call from getData , since it is easier for unit testing. I will not need to scoff at the configuration, I can just pass the array.

In my current service.yml there is a type definition:

 config: ... foo: class: Kopernikus\LeBundle\Service\Foo arguments: - @config 

I tried changing my definition of foo as factory methods with:

 foo: class: Kopernikus\LeBundle\Service\Foo arguments: - [@config, getData] 

but it also introduces the whole service.

How to insert the result of a service method as an argument to another service?

+6
source share
2 answers

You can achieve this with an expression language ( New in Symfony 2.4 )

As described in the document here, you can do something as an example:

 config: ... foo: class: Kopernikus\LeBundle\Service\Foo arguments: ["@=service('config').getData()"] 

Hope for this help

+8
source

Basically you are requesting a container for dependency injection. Can you create your own, which has a simple get() function (e.g.) that returns a new instance of Foo ? You can define it to create new objects every time you call get() or more than one singlet that always returns the same object (by storing it in a private static variable).

eg,

 <?php class FooContainer implements YourContainerInterface { public static function get() { // Config logic here return new Foo($config); } } 
0
source

All Articles