Load different .env file with a Symfony 4 command

孤街醉人 提交于 2020-01-14 03:03:23

问题


.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!