php 在 Laravel 5 中设置 ENV 变量的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26346299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the correct way to set ENV variables in Laravel 5?
提问by Alexander Kim
In laravel 4 we had:
在 Laravel 4 中,我们有:
$env = $app->detectEnvironment(array(
'local' => array('homestead')
));
by default.
默认情况下。
But in laravel 5 it's changed to:
但是在 Laravel 5 中它变成了:
$env = $app->detectEnvironment(function()
{
return getenv('APP_ENV') ?: 'production';
});
Also, they have excluded .env.*line in .gitignore, now it has:
此外,他们在 .gitignore 中排除了.env.*行,现在它有:
.env
And added file .env.example:
并添加了文件 .env.example:
APP_ENV=local
APP_KEY=SomeRandomString
DB_USERNAME=homestead
DB_PASSWORD=homestead
So, if i have more than 2 environments, do i have to set all of them in a single .env file now? E.g.:
那么,如果我有 2 个以上的环境,我现在是否必须将它们全部设置在一个 .env 文件中?例如:
APP_ENV=local
DB_PASSWORD=123
APP_ENV=alpha
DB_PASSWORD=456
If i would have no .env file, how laravel will know what environment i am using?
如果我没有 .env 文件,laravel 如何知道我使用的是什么环境?
回答by Marcin Nabia?ek
You can do it exactly the same as in Laravel 4:
你可以像在 Laravel 4 中一样做到这一点:
$env = $app->detectEnvironment(array(
'local' => array('homestead')
));
*.env
file are just used to put sensitive data that shouldn't be put into VCS. The same is in Laravel 4
*.env
文件仅用于放置不应放入 VCS 的敏感数据。在 Laravel 4 中也是如此
but is seems that in last days default detectEnvironment was changed to:
但似乎在最后几天默认检测环境已更改为:
$env = $app->detectEnvironment(function()
{
return getenv('APP_ENV') ?: 'production';
});
so you can use either setting variable from PC name or from ENV file.
因此您可以使用来自 PC 名称或 ENV 文件的设置变量。
If you use ENV based environment detection in main env file (by default .env
file you need to add:
如果您在主 env 文件中使用基于 ENV 的环境检测(默认情况下,.env
您需要添加:
APP_ENV=local
Of course local
here is local environment, you can change it into production
or dev
当然local
这里是本地环境,你可以改成production
或者dev
At the moment the most important issue I see is that you need to remember when going on production to change this .env
file content from APP_ENV=local
to APP_ENV=production
so in my opinion much better method is the old default method based on PC names.
目前我看到的最重要的问题是,您需要记住在进行生产时将此.env
文件内容从更改为APP_ENV=local
,APP_ENV=production
因此我认为更好的方法是基于 PC 名称的旧默认方法。
Now ENV files. If you use ENV based environment detection, you should put into your ENV file only:
现在是 ENV 文件。如果你使用基于 ENV 的环境检测,你应该只放入你的 ENV 文件:
APP_ENV=local
Now you can create separate ENV files for your different environments for example:
现在您可以为不同的环境创建单独的 ENV 文件,例如:
.local.env:
.local.env:
MY_DB=testdb
.production.env:
.production.env:
MY_DB=productiondb
and now in bootstrap.environment.php
file you can modfiy:
现在在bootstrap.environment.php
文件中你可以修改:
if (file_exists(__DIR__.'/../.env'))
{
Dotenv::load(__DIR__.'/../');
}
into:
进入:
if (file_exists(__DIR__.'/../.env'))
{
Dotenv::load(__DIR__.'/../');
if (getenv('APP_ENV') && file_exists(__DIR__.'/../.' .getenv('APP_ENV') .'.env')) {
Dotenv::load(__DIR__ . '/../', '.' . getenv('APP_ENV') . '.env');
}
}
to load extra env file based on APP_ENV
from main env file.
根据APP_ENV
主 env 文件加载额外的env 文件。
Now you will be able to use it in your other configuration file as always: $_ENV['MY_DB']
现在您可以像往常一样在其他配置文件中使用它: $_ENV['MY_DB']
回答by Hirnhamster
For those who just upgraded to 5.2:
对于刚刚升级到 5.2 的用户:
You cannot longer use the static Dotenv::load()
method. Use the following instead:
您不能再使用静态Dotenv::load()
方法。请改用以下内容:
$dotenv = new Dotenv\Dotenv(__DIR__ . '/../', '.' . getenv('APP_ENV') . '.env'); // Laravel 5.2
$dotenv->load();
in bootstrap/app.php
.
在bootstrap/app.php
。
//edit Soo.. after digging into this for the past hour I might as well add some additional info here:
//edit Soo ..在过去一个小时深入研究后,我不妨在这里添加一些额外的信息:
- Laravel uses .env files for configuration
- By default, the file ".env" in the root directory of the application is loaded
- You can access the values within those .env files via the
env()
helper function or directly via PHP's nativegetenv()
function. Although you should only do so to fill your config files (see/config/*.php
), because those can be cached. - the .env files are loaded in the DetectEnvironmentclass. I found this helpful while debugging to set breakpoints. Please take note of the line
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
: Since it usesload()
any environment value that has already been set will not be overwritten!(You would have to useoverload()
to do so - this drove me nutsbecause homestead sets theAPP_ENV
variable tolocal
in the php-fpm config/etc/php/7.0/fpm/php-fpm.conf
and you cannot change it via .env file) - when writing unit tests, you usually inherit from
TestCase
, which sets theAPP_ENV
variable to testing (viarefreshApplication()
-- usingputenv()
to override the defaultlocal
value)
- Laravel 使用 .env 文件进行配置
- 默认加载应用根目录下的“.env”文件
- 您可以通过
env()
辅助函数或直接通过 PHP 的本机getenv()
函数访问这些 .env 文件中的值。尽管您应该这样做只是为了填充您的配置文件(请参阅 参考资料/config/*.php
),因为它们可以被缓存。 - .env 文件加载在DetectEnvironment类中。我发现这在调试设置断点时很有帮助。请注意这一行
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
:由于它使用了任何已经设置的环境值,因此不会被覆盖!(你必须这样做 - 这让我发疯了,因为 homestead在 php-fpm 配置中设置了变量,你不能通过 .env 文件更改它)load()
overload()
APP_ENV
local
/etc/php/7.0/fpm/php-fpm.conf
- 编写单元测试时,您通常继承自
TestCase
,它将APP_ENV
变量设置为测试(通过refreshApplication()
--putenv()
用于覆盖默认local
值)
回答by thefuzzy0ne
I just wanted to contribute my solution for Laravel 5.1, which is slightly simpler IMHO. In bootstrap/app.php, I have (just after where the Application is instantiated):
我只是想为 Laravel 5.1 贡献我的解决方案,恕我直言,它稍微简单一些。在 bootstrap/app.php 中,我有(就在应用程序实例化之后):
$app->beforeBootstrapping(\Illuminate\Foundation\Bootstrap\DetectEnvironment::class, function() use ($app) {
$suffix = (env('APP_ENV'))
? '.'.env('APP_ENV')
: '';
$app->loadEnvironmentFrom('.env'.$suffix);
});
There's no need for any checking or error handling. Laravel will default to "production" if the file is not found.
不需要任何检查或错误处理。如果找不到文件,Laravel 将默认为“生产”。
That is all.
就这些。
回答by Shauna
The fact that you can't have more than one .env
file by default andthat it's excluded in .gitignore is intentional and is the intended way to manage environments. The .env
file should not be in version control and should be configured per environment. .env
sets your environment and all environment variables.
.env
默认情况下您不能拥有多个文件并且它被排除在 .gitignore 中这一事实是有意的,并且是管理环境的预期方式。该.env
文件不应处于版本控制中,应根据环境进行配置。.env
设置您的环境和所有环境变量。
So, if i have more than 2 environments, do i have to set all of them in a single .env file now?
那么,如果我有 2 个以上的环境,我现在是否必须将它们全部设置在一个 .env 文件中?
No. You would have a .env
file in each place that you have your application installed. The difference is in what is inside that file.
不可以。.env
在安装应用程序的每个位置都会有一个文件。不同之处在于该文件中的内容。
Additionally, because the .env
file is simply a key-value store, any subsequent declarations would overwrite previous ones. In your example, Laravel would never see your "local" settings.
此外,因为该.env
文件只是一个键值存储,任何后续声明都会覆盖之前的声明。在您的示例中,Laravel 永远不会看到您的“本地”设置。
It seems odd at first, but this new default system is actually generally easier and less prone to the issues the "4.2 way" had/has, as there's no place for logic errors.
乍一看似乎很奇怪,但这个新的默认系统实际上通常更容易,也更不容易出现“4.2 方式”所拥有/拥有的问题,因为没有逻辑错误的地方。
If i would have no .env file, how laravel will know what environment i am using?
如果我没有 .env 文件,laravel 如何知道我使用的是什么环境?
It wouldn't run at all. In the .env
file is also an APP_KEY
declaration, which Laravel will not run without. Without a .env
file, you would get a 500 server error.
它根本不会运行。在.env
文件也是一个APP_KEY
声明,这将Laravel没有运行。如果没有.env
文件,您将收到 500 服务器错误。