在Symfony 4应用程序中,如何将环境变量传递给服务类?

Pat*_*ick 0 php environment-variables symfony docker

我正在使用Symfony 4和Docker创建一个应用程序。在我的.env文件中,有以下几行:

DEVICE_CREATION_SECRET=123456
Run Code Online (Sandbox Code Playgroud)

...并且在我的services.yaml文件中,我具有以下定义:

VMS\Application\DigitalRetail\Handler\DeviceForwardHandler:
    arguments:
        - env(DEVICE_CREATION_SECRET)
Run Code Online (Sandbox Code Playgroud)

...我希望将我的秘密(123456)传递给我的班级,因为我在该班级中有以下内容:

public function __construct(string $deviceCreationSecret)
{
    $this->deviceCreationSecret = $deviceCreationSecret;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行我的应用程序并转储该值时,我得到的env(DEVICE_CREATION_SECRET)就是我的秘密(123456)。我需要什么才能访问该秘密?

Fla*_*ash 5

我认为这种方式应该可行:

VMS\Application\DigitalRetail\Handler\DeviceForwardHandler:
    arguments:
        - '%env(DEVICE_CREATION_SECRET)%'
Run Code Online (Sandbox Code Playgroud)

https://symfony.com/doc/current/configuration/external_parameters.html


Ayt*_*Nzt 5

转到 services.yml:

parameters:
    DEVICE_CREATION_SECRET: '%env(DEVICE_CREATION_SECRET)%'
Run Code Online (Sandbox Code Playgroud)

之后,在类上,注入parameterBagInterface:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

private $deviceCreationSecret;
private $params;

public function __construct(
    string $deviceCreationSecret,
    ParameterBagInterface $params
)
{
    $this->deviceCreationSecret = $deviceCreationSecret;
    $this->params = $params;
}
Run Code Online (Sandbox Code Playgroud)

然后,对于获取参数:

$this->params->get('DEVICE_CREATION_SECRET');
Run Code Online (Sandbox Code Playgroud)