问题
.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
回答1:
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;
}
来源:https://stackoverflow.com/questions/49345965/load-different-env-file-with-a-symfony-4-command