Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject method result of a service as an argument for another service?

I have a FooService that's fetches some data from another config service.

I have that config service as the config is different depending on the request data. The config service has the RequestStack injected and builds the relevant config array.

My FooService looks as follows:

class Foo
{
    private $config;

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

Yet instead of injecting the service, I prefer to inject only the method call result of getData, as it is simpler for unit testing. I won't need to mock the config, I can just pass an array.

My current service.yml has a definition like:

config:
    ...

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

I tried changing my foo definition like for factory methods via:

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

yet this too injects the whole service.

How to inject method result of a service as an argument for another service?

like image 907
k0pernikus Avatar asked Dec 10 '15 16:12

k0pernikus


1 Answers

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

As described in the doc here you can do something as example:

config:
    ...

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

Hope this help

like image 165
Matteo Avatar answered Nov 17 '22 22:11

Matteo