douyi6818 2019-08-09 14:23
浏览 127
已采纳

Symfony 4控制台命令无法读取env变量

I have a small console command where I'd like to read some environment variables, but it does not seem to read the vars from the .env file or the server configs in the console (php file works)

The code

protected function execute(InputInterface $input, OutputInterface $output)
{
    $io = new SymfonyStyle($input, $output);
    $debug = $input->getArgument('debug') === 'y' ? true : false;
    $this->project = $input->getArgument('project');

    $start = new DateTime();

    $debug ? $io->text('<fg=green>Starting upload</>') : null;
    dump(getenv('APP_ENV'));
    dump(getenv('MAILER_USERNAME'));
    die;
    ...
}

Commands to test

php bin/console app:make-backup

Output:

Starting upload
false
false

php bin/console app:make-backup --env=prod

Output:

Starting upload
"prod"
false

php bin/console app:make-backup --env=dev

Output:

Starting upload
"dev"
false

.env File

APP_ENV=dev
MAILER_USERNAME=info@xxx.com

I don't see where I am doing wrong? Issue exists on nginx and apache server, BUT using getenv('MAILER_USERNAME') in any php-file works.

  • 写回答

1条回答 默认 最新

  • douyong8801 2019-08-09 14:51
    关注

    I think your best bet would be to go ahead and inject the env variables. Trying to access them directly can be a bit tricky.

    # config/services.yaml
    services:
        App\Command\MyCommand:
            $appEnv:         '%env(APP_ENV)%'
            $mailerUsername: '%env(MAILER_USERNAME)%'
    
    # src\Command\MyCommand
    class MyCommand extends Command {
        protected static $defaultName = 'app:mine';
    
        private $appEnv;
        private $mailerUsername;
    
        public function __construct($appEnv,$mailerUsername) {
            parent::__construct();
            $this->appEnv = $appEnv;
            $this->mailerUsername = $mailerUsername;
        }
        protected function execute(InputInterface $input, OutputInterface $output) {
            $output->writeln(("My Command " . $this->appEnv . " " . $this->mailerUsername));
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    悬赏问题

    • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
    • ¥15 要求编写稀疏矩阵A的转置矩阵的算法
    • ¥15 编写满足以下要求的停车场管理程序,设停车场只有一个可停放n辆车的狭窄通道且只有一个大门可供车辆进出。
    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥15 用keil调试程序保证结果进行led相关闪烁
    • ¥15 paddle训练自己的数据loss降不下去
    • ¥20 用matlab的pdetool解决以下三个问题
    • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
    • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
    • ¥20 h3c静态路要求有详细过程