简而言之,2022 年最新情况:
-
use env()
仅在配置文件中
-
use App::environment()
用于检查环境(.env 中的 APP_ENV)。
-
use config('app.var')
对于所有其他环境变量,例如:config('app.debug')
-
为您自己的 ENV 变量创建自己的配置文件。例子:
在你的 .env 中:
MY_VALUE=foo
example config/myconfig.php
return [
'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];
在您的代码中访问:
config('myconfig.myvalue') // will result in 'foo'
解释和历史:
我只是感觉了一下。当您缓存配置文件时,env()
会(有时?)无法正常工作。所以我发现:
- Laravel 建议仅使用
env()
在配置文件中。使用config()
代码中的助手而不是env()
。例如你可以打电话config('app.env')
在你的代码中。
- 当你使用
php artisan config:cache
所有配置字符串都由框架缓存,并且您对配置进行的任何更改.env
在运行以下命令之前,文件不会处于活动状态php artisan config:cache
再次命令。
From 本文 https://laracasts.com/discuss/channels/general-discussion/env-not-reading-variables-sometimes在 Laracast 上:
UPDATE:
env()
只要您不使用,通话就可以使用php artisan config:cache
。所以这是非常危险的,因为它经常在开发时起作用但在生产时会失败. See 升级指南 https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0
缓存和环境
如果您在部署期间使用 config:cache 命令,则必须
确保您只从您的内部调用 env 函数
配置文件,而不是来自应用程序中的其他任何地方。
如果您从应用程序内调用 env,则强烈要求
建议您在配置中添加适当的配置值
文件并从该位置调用 env,从而允许您转换
你的环境调用配置调用。
更新 Laravel 5.6:
Laravel 现在在其推荐中文档 https://laravel.com/docs/9.x/configuration#determining-the-current-environment to use
$environment = App::environment();
// or check on an array of environments:
if (App::environment(['local', 'staging'])) {
// The environment is either local OR staging...
}
and 描述 https://laravel.com/docs/9.x/configuration#retrieving-environment-configuration that env()
只是从中检索值.env
在配置文件中,例如config('app.env')
or config('app.debug')
.