需要注意的是寫這篇筆記的時候對應
Laravel
版本是6.x
如何支援多 ENV 檔案?
首先通過搜尋引擎瞭解到可以通過在啟動檔案 bootstrap/app.php
中呼叫如下方法重新指定要讀取的配置檔案:
$app->loadEnvironmentFrom(
'自定義.env'
);
但是隨之而來的就是報錯因為網上的文件是基於 5.x
的版本,於是就利用 PHPStorm
的追蹤功能進入了其原始碼中:
/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadEnvironmentVariables.php
/**
* Set the directory for the environment file.
*
* @param string $path
* @return $this
*/
public function useEnvironmentPath($path)
{
$this->environmentPath = $path;
return $this;
}
/**
* Set the environment file to be loaded during bootstrapping.
*
* @param string $file
* @return $this
*/
public function loadEnvironmentFrom($file)
{
$this->environmentFile = $file;
return $this;
}
注意到此方法的上一行方法了麼?沒錯看註釋就已經非常明白了:設定讀取配置檔案的目錄,所以只要將這兩個搭配起來使用即可實現讀取自定義的 env
配置檔案:
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
// 此處為新增的改寫部分:基於域名來讀取 __env 目錄下的配置檔案
$app->useEnvironmentPath(
__DIR__ . '/../__env'
);
$app->loadEnvironmentFrom(
'.' . $_SERVER['SERVER_NAME'] .'.env'
);
參考文獻
本作品採用《CC 協議》,轉載必須註明作者和本文連結