繁体   English   中英

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

[英]In a Symfony 4 application, how do I pass an environment variable to a service class?

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

DEVICE_CREATION_SECRET=123456

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

VMS\Application\DigitalRetail\Handler\DeviceForwardHandler:
    arguments:
        - env(DEVICE_CREATION_SECRET)

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

public function __construct(string $deviceCreationSecret)
{
    $this->deviceCreationSecret = $deviceCreationSecret;
}

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

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

VMS\Application\DigitalRetail\Handler\DeviceForwardHandler:
    arguments:
        - '%env(DEVICE_CREATION_SECRET)%'

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

转到services.yml:

parameters:
    DEVICE_CREATION_SECRET: '%env(DEVICE_CREATION_SECRET)%'

之后,在该类上,注入parameterBagInterface:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

private $deviceCreationSecret;
private $params;

public function __construct(
    string $deviceCreationSecret,
    ParameterBagInterface $params
)
{
    $this->deviceCreationSecret = $deviceCreationSecret;
    $this->params = $params;
}

然后,对于get参数:

$this->params->get('DEVICE_CREATION_SECRET');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM