CakePHP で .env を使う方法
CakePHP では .env に設定値を逃して env() で読み込むことができると Cookbook: 構成設定 – 5.x に説明されている。だがしかし、説明のとおり.env.example を.env にコピーしても反映されない。(Cookbook は、.env.default となっているが実際のファイルは、.env.examlpe となっている。んー。)
検索すると Qiita にそれっぽいのがあったのでやってみるとビンゴだった。
bootstrap.php の中で .env をロードする処理がコメントアウトされているためだった。
/*
* See https://github.com/josegonzalez/php-dotenv for API details.
*
* Uncomment block of code below if you want to use `.env` file during development.
* You should copy `config/.env.example` to `config/.env` and set/modify the
* variables as required.
*
* The purpose of the .env file is to emulate the presence of the environment
* variables like they would be present in production.
*
* If you use .env files, be careful to not commit them to source control to avoid
* security risks. See https://github.com/josegonzalez/php-dotenv#general-security-information
* for more information for recommended practices.
*/
if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
$dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
$dotenv->parse()
->putenv()
->toEnv()
->toServer();
}
今回、.env ファイルに DB 周りの設定を逃してみた。
こんな感じでホスト名やDB関連のパラメータを設定すると
export DB_HOST="maria"
export DB_ROOT="root"
export DB_ROOT_PASS="DBPASSWORD!"
export DB_NAME="CAKE_DATABASE"
export DB_USER="user"
export DB_PASS="PASSWORD"
app_local.php で env() で読み込む
return[
// 一部抜粋
'Datasources' => [
'default' => [
'host' => env('DB_HOST', null),
'username' => env('DB_USER', null),
'password' => env('DB_PASS', null),
'database' => env('DB_NAME', null),
//'schema' => 'myapp',
],
// 抜粋終わり
CakePHP のドキュメントは割とわかりやすいので嫌いではないが、app_local.php や .env 周辺の説明は相変わらずファイル名の間違いや記述の不足があってわかりにくい。
このへんなんとかならないかな。