LoginSignup
17
16

More than 5 years have passed since last update.

CakePHP3で.envファイルを有効化する

Last updated at Posted at 2018-06-01

概要

CakePHP3.5から.envの利用が標準化されました。

.env利用の流れ

  • configフォルダ配下にある.env.default.envにリネームする
  • .envに設定を記述する。
config/.env
export DB_HOST="hoge_host"
export DB_USERNAME="hoge"
export DB_PASSWORD="hoge"
export DB_DATABASE="hoge"
  • config/app.phpに.envの値を設定する。app.phpがない場合は、app.php.defaultをリネームする。
config/app.php
'Datasources' => [
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => env('DB_HOST'),
        /*
         * CakePHP will use the default DB port based on the driver selected
         * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
         * the following line and set the port accordingly
         */
        //'port' => 'non_standard_port_number',
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'database' => env('DB_DATABASE'),
  • config/bootstrap.phpの以下をコメント解除する。コメント解除しないと.envは有効にならないので要注意。
config/bootstrap.php
if (!env('APP_NAME') && file_exists(CONFIG . '.env')) {
    $dotenv = new \josegonzalez\Dotenv\Loader([CONFIG . '.env']);
    $dotenv->parse()
        ->putenv()
        ->toEnv()
        ->toServer();
}

最後に

.envはバージョン管理からは除外しておきましょう。

17
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
16