How to access an application parameters from a service?

Pierre de LESPINAY picture Pierre de LESPINAY · Jun 26, 2012 · Viewed 72.2k times · Source

From my controllers, I access the application parameters (those in /app/config) with

$this->container->getParameter('my_param')

But I don't know how to access it from a service (I imagine my service class is not supposed to extend Symfony\Bundle\FrameworkBundle\Controller\Controller).

Should I map needed parameters into my service registration like this:

#src/Me/MyBundle/Service/my_service/service.yml
parameters:
    my_param1: %my_param1%
    my_param2: %my_param2%
    my_param3: %my_param3%

or something similar? How should I access to my application parameters from a service?


This question seems like the same but mine actually answers to it (parameters from a controller), I'm talking about accessing from a service.

Answer

richsage picture richsage · Jun 26, 2012

You can pass parameters to your service in the same way as you inject other services, by specifying them in your service definition. For example, in YAML:

services:
    my_service:
        class:  My\Bundle\Service\MyService
        arguments: [%my_param1%, %my_param2%]

where the %my_param1% etc corresponds to a parameter named my_param1. Then your service class constructor could then be:

public function __construct($myParam1, $myParam2)
{
    // ...
}