关于Lumen(Laravel)中.env文件中的环境变量是如何生效的

.env 文件可自定义其他任何有效的环境变量,并可通过 调用 env() 或 $_SERVER 或 $_ENV 来获取该变量。那么env()是如何加载到这些变量的呢?

函数env():在Lumen的vendor/laravel/lumen-framework/src/helpers.php中,我们可以发现env函数是这样被定义的:

可见,env函数中调用了 getenv() 来读取环境变量。

vlucas/phpdotenv:我们知道getenv()是PHP原生提供可读取 $_SERVER 或 $_ENV 全局变量的函数API,.env文件中的环境变量为何可以通过getenv()来获取呢?vlucas/phpdotenv就是这个幕后功臣,在Lumen 或 Laravel 的vendor下可以找到她,如果要单独下载她,去这里。在vlucas/phpdotenv/src/Loader.php文件中,我们可以看到.env被加载进一个数组,然后把每一行看作setter并调用setEnvironmentVariable()方法:

Loader::setEnvironmentVariable($name, $value = null) 的定义如下:

PHP dotenv 是什么:

Loads environment variables from .env to getenv(), $_ENV and $_SERVER automagically.This is a PHP version of the original Ruby dotenv.

Why .env:

You should never store sensitive credentials in your code. Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments – such as database credentials or credentials for 3rd party services – should be extracted from the code into environment variables.Basically, a .env file is an easy way to load custom configuration variables that your application needs without having to modify .htaccess files or Apache/nginx virtual hosts. This means you won’t have to edit any files outside the project, and all the environment variables are always set no matter how you run your project - Apache, Nginx, CLI, and even PHP 5.4’s built-in webserver. It’s WAY easier than all the other ways you know of to set environment variables, and you’re going to love it.. NO editing virtual hosts in Apache or Nginx. NO adding php_value flags to .htaccess files. EASY portability and sharing of required ENV values. COMPATIBLE with PHP’s built-in web server and CLI runner

关注作者公众号,获取更多资源!
赏作者一杯咖啡~