Laravel核心解讀--ENV的加載和讀取

Laravel在啓動時會加載項目中的.env文件。對於應用程序運行的環境來說,不同的環境有不同的配置通常是很有用的。 例如,你可能希望在本地使用測試的Mysql數據庫而在上線後希望項目能夠自動切換到生產Mysql數據庫。本文將會詳細介紹 env 文件的使用與源碼的分析。

Env文件的使用

多環境env的設置

項目中env文件的數量往往是跟項目的環境數量相同,假如一個項目有開發、測試、生產三套環境那麼在項目中應該有三個.env.dev.env.test.env.prod三個環境配置文件與環境相對應。三個文件中的配置項應該完全一樣,而具體配置的值應該根據每個環境的需要來設置。

接下來就是讓項目能夠根據環境加載不同的env文件了。具體有三種方法,可以按照使用習慣來選擇使用:

  • 在環境的nginx配置文件裏設置APP_ENV環境變量fastcgi_param APP_ENV dev;
  • 設置服務器上運行PHP的用戶的環境變量,比如在www用戶的/home/www/.bashrc中添加export APP_ENV dev
  • 在部署項目的持續集成任務或者部署腳本里執行cp .env.dev .env

針對前兩種方法,Laravel會根據env('APP_ENV')加載到的變量值去加載對應的文件.env.dev.env.test這些。 具體在後面源碼裏會說,第三種比較好理解就是在部署項目時將環境的配置文件覆蓋到.env文件裏這樣就不需要在環境的系統和nginx裏做額外的設置了。

自定義env文件的路徑與文件名

env文件默認放在項目的根目錄中,laravel 爲用戶提供了自定義 ENV 文件路徑或文件名的函數,

例如,若想要自定義 env 路徑,可以在 bootstrap 文件夾中 app.php 中使用Application實例的useEnvironmentPath方法:

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

$app->useEnvironmentPath('/customer/path')

若想要自定義 env 文件名稱,就可以在 bootstrap 文件夾中 app.php 中使用Application實例的loadEnvironmentFrom方法:

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

$app->loadEnvironmentFrom('customer.env')

Laravel 加載ENV配置

Laravel加載ENV的是在框架處理請求之前,bootstrap過程中的LoadEnvironmentVariables階段中完成的。

我們來看一下\Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables的源碼來分析下Laravel是怎麼加載env中的配置的。

<?php

namespace Illuminate\Foundation\Bootstrap;

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Symfony\Component\Console\Input\ArgvInput;
use Illuminate\Contracts\Foundation\Application;

class LoadEnvironmentVariables
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if ($app->configurationIsCached()) {
            return;
        }

        $this->checkForSpecificEnvironmentFile($app);

        try {
            (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
        } catch (InvalidPathException $e) {
            //
        }
    }

    /**
     * Detect if a custom environment file matching the APP_ENV exists.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    protected function checkForSpecificEnvironmentFile($app)
    {
        if ($app->runningInConsole() && ($input = new ArgvInput)->hasParameterOption('--env')) {
            if ($this->setEnvironmentFilePath(
                $app, $app->environmentFile().'.'.$input->getParameterOption('--env')
            )) {
                return;
            }
        }

        if (! env('APP_ENV')) {
            return;
        }

        $this->setEnvironmentFilePath(
            $app, $app->environmentFile().'.'.env('APP_ENV')
        );
    }

    /**
     * Load a custom environment file.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  string  $file
     * @return bool
     */
    protected function setEnvironmentFilePath($app, $file)
    {
        if (file_exists($app->environmentPath().'/'.$file)) {
            $app->loadEnvironmentFrom($file);

            return true;
        }

        return false;
    }
}

在他的啓動方法bootstrap中,Laravel會檢查配置是否緩存過以及判斷應該應用那個env文件,針對上面說的根據環境加載配置文件的三種方法中的頭兩種,因爲系統或者nginx環境變量中設置了APP_ENV,所以Laravel會在checkForSpecificEnvironmentFile方法里根據 APP_ENV的值設置正確的配置文件的具體路徑, 比如.env.dev或者.env.test,而針對第三中情況則是默認的.env, 具體可以參看下面的checkForSpecificEnvironmentFile還有相關的Application裏的兩個方法的源碼:

protected function checkForSpecificEnvironmentFile($app)
{
    if ($app->runningInConsole() && ($input = new ArgvInput)->hasParameterOption('--env')) {
        if ($this->setEnvironmentFilePath(
            $app, $app->environmentFile().'.'.$input->getParameterOption('--env')
        )) {
            return;
        }
    }

    if (! env('APP_ENV')) {
        return;
    }

    $this->setEnvironmentFilePath(
        $app, $app->environmentFile().'.'.env('APP_ENV')
    );
}

namespace Illuminate\Foundation;
class Application ....
{

    public function environmentPath()
    {
        return $this->environmentPath ?: $this->basePath;
    }
    
    public function environmentFile()
    {
        return $this->environmentFile ?: '.env';
    }
}

判斷好後要讀取的配置文件的路徑後,接下來就是加載env裏的配置了。

(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();

Laravel使用的是Dotenv的PHP版本vlucas/phpdotenv

class Dotenv
{
    public function __construct($path, $file = '.env')
    {
        $this->filePath = $this->getFilePath($path, $file);
        $this->loader = new Loader($this->filePath, true);
    }

    public function load()
    {
        return $this->loadData();
    }

    protected function loadData($overload = false)
    {
        $this->loader = new Loader($this->filePath, !$overload);

        return $this->loader->load();
    }
}

它依賴/Dotenv/Loader來加載數據:

class Loader
{
    public function load()
    {
        $this->ensureFileIsReadable();

        $filePath = $this->filePath;
        $lines = $this->readLinesFromFile($filePath);
        foreach ($lines as $line) {
            if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
                $this->setEnvironmentVariable($line);
            }
        }

        return $lines;
    }
}

Loader讀取配置時readLinesFromFile函數會用file函數將配置從文件中一行行地讀取到數組中去,然後排除以#開頭的註釋,針對內容中包含=的行去調用setEnvironmentVariable方法去把文件行中的環境變量配置到項目中去:

namespace Dotenv;
class Loader
{
    public function setEnvironmentVariable($name, $value = null)
    {
        list($name, $value) = $this->normaliseEnvironmentVariable($name, $value);

        $this->variableNames[] = $name;

        // Don't overwrite existing environment variables if we're immutable
        // Ruby's dotenv does this with `ENV[key] ||= value`.
        if ($this->immutable && $this->getEnvironmentVariable($name) !== null) {
            return;
        }

        // If PHP is running as an Apache module and an existing
        // Apache environment variable exists, overwrite it
        if (function_exists('apache_getenv') && function_exists('apache_setenv') && apache_getenv($name)) {
            apache_setenv($name, $value);
        }

        if (function_exists('putenv')) {
            putenv("$name=$value");
        }

        $_ENV[$name] = $value;
        $_SERVER[$name] = $value;
    }
    
    public function getEnvironmentVariable($name)
    {
        switch (true) {
            case array_key_exists($name, $_ENV):
                return $_ENV[$name];
            case array_key_exists($name, $_SERVER):
                return $_SERVER[$name];
            default:
                $value = getenv($name);
                return $value === false ? null : $value; // switch getenv default to null
        }
    }
}

Dotenv實例化Loader的時候把Loader對象的$immutable屬性設置成了falseLoader設置變量的時候如果通過getEnvironmentVariable方法讀取到了變量值,那麼就會跳過該環境變量的設置。所以Dotenv默認情況下不會覆蓋已經存在的環境變量,這個很關鍵,比如說在docker的容器編排文件裏,我們會給PHP應用容器設置關於Mysql容器的兩個環境變量

    environment:
      - "DB_PORT=3306"
      - "DB_HOST=database"

這樣在容器裏設置好環境變量後,即使env文件裏的DB_HOSThomesteadenv函數讀取出來的也還是容器裏之前設置的DB_HOST環境變量的值database(docker中容器鏈接默認使用服務名稱,在編排文件中我把mysql容器的服務名稱設置成了database, 所以php容器要通過database這個host來連接mysql容器)。因爲用我們在持續集成中做自動化測試的時候通常都是在容器裏進行測試,所以Dotenv不會覆蓋已存在環境變量這個行爲就相當重要這樣我就可以只設置容器裏環境變量的值完成測試而不用更改項目裏的env文件,等到測試完成後直接去將項目部署到環境上就可以了。

如果檢查環境變量不存在那麼接着Dotenv就會把環境變量通過PHP內建函數putenv設置到環境中去,同時也會存儲到$_ENV$_SERVER這兩個全局變量中。

在項目中讀取env配置

在Laravel應用程序中可以使用env()函數去讀取環境變量的值,比如獲取數據庫的HOST:

env('DB_HOST`, 'localhost');

傳遞給 env 函數的第二個值是「默認值」。如果給定的鍵不存在環境變量,則會使用該值。

我們來看看env函數的源碼:

function env($key, $default = null)
{
    $value = getenv($key);

    if ($value === false) {
        return value($default);
    }

    switch (strtolower($value)) {
        case 'true':
        case '(true)':
            return true;
        case 'false':
        case '(false)':
            return false;
        case 'empty':
        case '(empty)':
            return '';
        case 'null':
        case '(null)':
            return;
    }

    if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) {
        return substr($value, 1, -1);
    }

    return $value;
}

它直接通過PHP內建函數getenv讀取環境變量。

我們看到了在加載配置和讀取配置的時候,使用了putenvgetenv兩個函數。putenv設置的環境變量只在請求期間存活,請求結束後會恢復環境之前的設置。因爲如果php.ini中的variables_order配置項成了 GPCS不包含E的話,那麼php程序中是無法通過$_ENV讀取環境變量的,所以使用putenv動態地設置環境變量讓開發人員不用去關注服務器上的配置。而且在服務器上給運行用戶配置的環境變量會共享給用戶啓動的所有進程,這就不能很好的保護比如DB_PASSWORDAPI_KEY這種私密的環境變量,所以這種配置用putenv設置能更好的保護這些配置信息,getenv方法能獲取到系統的環境變量和putenv動態設置的環境變量。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章