如何从服务访问应用程序参数?

问题描述:

从我的控制器中,我使用

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

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

但我不知道如何从服务访问它(我想我的服务类不应该扩展 Symfony\Bundle\FrameworkBundle\Controller\Controller).

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.

您可以通过在服务定义中指定参数,以与注入其他服务相同的方式将参数传递给您的服务.例如,在 YAML 中:

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%]

其中 %my_param1% 等对应于名为 my_param1 的参数.那么你的服务类构造函数可以是:

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)
{
    // ...
}