June 17, 2016 · Symfony PHP Code Snippets

Using DotEnv (.env) in your Symfony project


tl;dr: How to set / get parameters with a .env DotEnv file instead of the Symfony standard app/config/parameters.yml.


I was recently deploying a Symfony 3 project via Envoyer.io (from Laravel's creator), and via their dashboard I can set the parameters to include in the .env file. It would set up the .env file after each deploy, because each deploy would create a new timestamped folder. Instead of writing my own script to use Symfony's parameters.yml file, I thought I'd try to use the DotEnv method for Symfony.

So here's a quick run-through on how I did it.

First, you will need to include the DotEnv library:

composer require vlucas/phpdotenv

Afterwards, you should change the AppKernel.php so it would load the .env file additionally to the yml parameter files:

// app/AppKernel.php

public function registerContainerConfiguration(LoaderInterface $loader)
{
    $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');

    try {
        (new Dotenv\Dotenv(__DIR__.'/../'))->load();
        $envParameters = $this->getEnvParameters();
        $loader->load(function($container) use($envParameters) {
            $container->getParameterBag()->add($envParameters);
        });
    } catch (Dotenv\Exception\InvalidPathException $e) {
        // don't do much at the moment, possibly the env variables are set differently (e.g. AWS)
    }

In order to use the variables, you will need to name them in this way:

# .env
SYMFONY__EXTERNAL_SERVICE_API_KEY='some-1234-apikey'

As described in the Symfony cookbook, Symfony will then modify them in this way:

  • SYMFONY__ prefix is removed;
  • Parameter name is lowercased;
  • Double underscores are replaced with a period, as a period is not a valid character in an environment variable name.

So now we have access to that parameter through external_service_api_key. You can now inject the key / parameters into services, like this:

# src/AppBundle/Resources/config/services.yml
services:
    some_cool_service:
        class: AppBundle\Service\CoolStuff
        arguments: ["%external_service_api_key%"]

If you need it in twig, you can write it into config.yml:

# app/config/config.yml
twig:
    globals:
        external_service_api_key: "%external_service_api_key%"

then in your twig file you can use it, such as

<script src="http://api.something.org/function.js?key={{ external_service_api_key }}">

That's it!

Since the .env file with the secret keys should not be committed to the repository, to make it a bit easier for other developers, consider creating a .env.dist file with the keys and placeholder values, so they only need to copy .env.dist to .env and insert the values.

This post was also inspired by
https://github.com/symfony/symfony/issues/7555#issuecomment-15856713
and B. Beberlei's post named "Symfony All The Things (Web)"

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket
Comments powered by Disqus