Thomas Decaux
Thomas Decaux

Reputation: 22671

Load different .env file with a Symfony 4 command

.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

Upvotes: 2

Views: 3323

Answers (2)

famas23
famas23

Reputation: 2280

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';

Upvotes: 0

Chris Brown
Chris Brown

Reputation: 4635

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;
}

Upvotes: 2

Related Questions