takaya030の備忘録

PHP、Laravel、Docker などの話がメインです

Lumen8 で環境変数 APP_ENV に応じて .env ファイルを切り替える

検証環境

Windows10 Home Edition (version 21H1)

$ php --version
PHP 7.4.9 (cli) (built: Aug  4 2020 11:52:41) ( ZTS Visual C++ 2017 x64 )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.9, Copyright (c), by Zend Technologies
    with Xdebug v2.8.1, Copyright (c) 2002-2019, by Derick Rethans

$ php artisan --version
Laravel Framework Lumen (8.2.4) (Laravel Components ^8.0)

Lumen8 の .env ファイルの読み込みについて

Lumen8 では bootstrap/app.php の先頭にある下記の部分で読み込んでいます

(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
    dirname(__DIR__)
))->bootstrap();

Laravel\Lumen\Bootstrap\LoadEnvironmentVariables クラスのソースを確認するとコンストラクタで .envディレクトリだけでなくファイル名も指定可能になっていました

vendor/laravel/lumen-framework/src/Bootstrap/LoadEnvironmentVariables.php

<?php

namespace Laravel\Lumen\Bootstrap;

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidFileException;
use Illuminate\Support\Env;
use Symfony\Component\Console\Output\ConsoleOutput;

class LoadEnvironmentVariables
{
    /**
     * The directory containing the environment file.
     *
     * @var string
     */
    protected $filePath;

    /**
     * The name of the environment file.
     *
     * @var string|null
     */
    protected $fileName;

    /**
     * Create a new loads environment variables instance.
     *
     * @param  string  $path
     * @param  string|null  $name
     * @return void
     */
    public function __construct($path, $name = null)
    {
        $this->filePath = $path;
        $this->fileName = $name;
    }

    /**
     * Setup the environment variables.
     *
     * If no environment file exists, we continue silently.
     *
     * @return void
     */
    public function bootstrap()
    {
        try {
            $this->createDotenv()->safeLoad();
        } catch (InvalidFileException $e) {
            $this->writeErrorAndDie([
                'The environment file is invalid!',
                $e->getMessage(),
            ]);
        }
    }

    /**
     * Create a Dotenv instance.
     *
     * @return \Dotenv\Dotenv
     */
    protected function createDotenv()
    {
        return Dotenv::create(
            Env::getRepository(),
            $this->filePath,
            $this->fileName
        );
    }

    /**
     * Write the error information to the screen and exit.
     *
     * @param  string[]  $errors
     * @return void
     */
    protected function writeErrorAndDie(array $errors)
    {
        $output = (new ConsoleOutput)->getErrorOutput();

        foreach ($errors as $error) {
            $output->writeln($error);
        }

        exit(1);
    }
}

環境変数 APP_ENV に応じて .env を切り替える変更

bootstrap/app.php を下記のように変更することで APP_ENV の値に応じて読み込む .env が切り替わります
例えば APP_ENV=prd のときは .env.prd が読み込まれます

bootstrap/app.php

$env = env('APP_ENV');
$env_file = '.env.'.$env;

if (!file_exists(dirname(__DIR__).'/'.$env_file)) {
    $env_file = null;
}

(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
    dirname(__DIR__),
    $env_file
))->bootstrap();