Tony Bogdanov Tony Bogdanov - 1 year ago 155
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
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 Source

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:


    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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download