[英]In a Symfony 4 application, how do I pass an environment variable to a service class?
I am creating an app using Symfony 4 and Docker. 我正在使用Symfony 4和Docker创建一个应用程序。 In my .env file, I have the following line: 在我的.env文件中,有以下几行:
DEVICE_CREATION_SECRET=123456
... and in my services.yaml file, I have the following definition: ...并且在我的services.yaml文件中,我具有以下定义:
VMS\Application\DigitalRetail\Handler\DeviceForwardHandler:
arguments:
- env(DEVICE_CREATION_SECRET)
... which I expect to hand off my secret (123456) to my class, since I have this in that class: ...我希望将我的秘密(123456)传递给我的班级,因为我在该班级中有以下几点:
public function __construct(string $deviceCreationSecret)
{
$this->deviceCreationSecret = $deviceCreationSecret;
}
But when I run my app and dump out the value, I get env(DEVICE_CREATION_SECRET)
rather then my secret (123456). 但是,当我运行我的应用并转储该值时,我得到的是env(DEVICE_CREATION_SECRET)
而不是我的秘密(123456)。 What do I need to get access to that secret? 我需要什么才能访问该秘密?
I think this way should work: 我认为这种方式应该可行:
VMS\Application\DigitalRetail\Handler\DeviceForwardHandler:
arguments:
- '%env(DEVICE_CREATION_SECRET)%'
https://symfony.com/doc/current/configuration/external_parameters.html https://symfony.com/doc/current/configuration/external_parameters.html
Go to services.yml: 转到services.yml:
parameters:
DEVICE_CREATION_SECRET: '%env(DEVICE_CREATION_SECRET)%'
After this, on the class, inject parameterBagInterface: 之后,在该类上,注入parameterBagInterface:
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
private $deviceCreationSecret;
private $params;
public function __construct(
string $deviceCreationSecret,
ParameterBagInterface $params
)
{
$this->deviceCreationSecret = $deviceCreationSecret;
$this->params = $params;
}
And then, for get parameter: 然后,对于get参数:
$this->params->get('DEVICE_CREATION_SECRET');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.