How do I get an environment parameter in a controller In Symfony 3.4?

ACJ picture ACJ · May 14, 2018 · Viewed 9k times · Source

In the dev environment of a Symfony 3.4 application, I am trying to store credentials as environment variables. I can’t get it to work, and I can’t figure out what’s missing. This is what I have:

In app\config\.env I have an API key defined, like so:

GOOGLE_DEVELOPER_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

In app\config\services.yml I have:

parameters:
    google.developer.key: "%env(GOOGLE_DEVELOPER_KEY)%"

In one of my controllers, I want to pass this parameter to an object like so:

    $client = new \Google_Client();
    $client->setDeveloperKey($this->getParameter('google.developer.key'));

To me, that setup looks fine, but when I try to run it, I get a EnvNotFoundException with the following message:

Environment variable not found: "GOOGLE_DEVELOPER_KEY".

When I put the key in app\config\services.yml directly, it works just fine:

parameters:
    google.developer.key: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

(But that’s not what I want, for a variety of reasons.)

I cleared the dev cache, restarted the web server, read the relevant Symfony Documentation (I think), but no luck. I guess I’m missing a step, but I can’t figure out what that would be. Any hints would be appreciated.

Answer

Francesco Abeni picture Francesco Abeni · May 14, 2018

Symfony 3.4 does not automatically load the .env file. You have to modify your app_dev.php to load the file:

use Symfony\Component\Dotenv\Dotenv;
...
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/../app/config/.env');