Tony Bogdanov Tony Bogdanov - 2 days ago 4
PHP Question

Symfony2: How to inject ALL parameters in a service?

How can I inject ALL parameters in a service?

I know I can do:

arguments: [%some.key%]
which will pass the
parameters: some.key: "value"
to the service __construct.

My question is, how to inject everything that is under
parameters
in the service?

I need this in order to make a navigation manager service, where different menus / navigations / breadcrumbs are to be generated according to different settings through all of the configuration entries.

I know I could inject as many parameters as I want, but since it is going to use a number of them and is going to expand as time goes, I think its better to pass the whole thing right in the beginning.

Other approach might be if I could get the parameters inside the service as you can do in a controller
$this -> container -> getParameter('some.key');
, but I think this would be against the idea of Dependency Injection?

Thanks in advance!

Answer

Note: I know that this solution is not BEST from design point of view, but it does the job, so please avoid down-voting.

You can inject \AppKernel object and then access all parameters like this:

config.yml:

my_service:
    class: MyService\Class
    arguments: [@kernel]

And inside MyService\Class:

public function __construct($kernel)
{
    $this->parameter = $kernel->getContainer()->getParameter('some.key');
    // or to get all:
    $this->parameters = $kernel->getContainer()->getParameterBag()->all();
}
Comments