Mayor of the Plattenbaus
Mayor of the Plattenbaus

Reputation: 1160

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. In my .env file, I have the following line:

DEVICE_CREATION_SECRET=123456

... and in my services.yaml file, I have the following definition:

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:

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). What do I need to get access to that secret?

Upvotes: 5

Views: 6896

Answers (2)

AythaNzt
AythaNzt

Reputation: 1057

Go to services.yml:

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

After this, on the class, inject 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:

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

Upvotes: 6

Flash
Flash

Reputation: 1204

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

Upvotes: 7

Related Questions