2

.env file is parsed when running a Symfony 4 command (if dotenv is available).

This is working fine when developping, but also, I want to test my code (so another environment), hence I need to load another .env file.

I love what Docker did to run a container:

docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash

So I am looking to achieve same thing with Symfony:

php bin/console --env-file ./.env.test 

right now, I am doing this:

export $(grep -v '^#' .env.test | xargs) && php bin/console
Thomas Decaux
  • 21,738
  • 2
  • 113
  • 124
  • I think the idea is that outside of development you are supposed to define your env variables elsewhere. If you look at the bin/console code you will see that it loads .env based on the existence of an external APP_ENV variable. Of course an easy work around is to just make a console_test. – Cerad Mar 18 '18 at 12:22
  • This is definitely something that should, IMO at least, be supported. Being able to run a command that, for example, executes tests and requires a different database requires a change in environment variable and being able to change that + n other vars by specifying a different file makes a lot of sense. – Chris Brown May 02 '18 at 21:05

2 Answers2

2

I opted for editing the bin/console file directly to facilitate the different .env file, which isn't an issue since it's a file the developer has control over. I updated the relevant section to;

if (!isset($_SERVER['APP_ENV'])) {
    if (!class_exists(Dotenv::class)) {
        throw new \RuntimeException('APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.');
    }
}

$input = new ArgvInput();
$env = $input->getParameterOption(['--env', '-e'], $_SERVER['APP_ENV'] ?? 'dev', true);

switch ($env) {
    case 'test':
        (new Dotenv())->load(__DIR__.'/../.env.test');
        break;

    case 'dev':
    default:
        (new Dotenv())->load(__DIR__.'/../.env');
        break;
}
Chris Brown
  • 4,445
  • 3
  • 28
  • 36
0

Make sure that your app/bootstrap.php and bin/console binary is well updated. In my case I just updated bin/console by adding :

require dirname(__DIR__).'/app/bootstrap.php';
famas23
  • 2,072
  • 4
  • 17
  • 53