laravel 使用 env('APP_ENV')、config('app.env') 或 App::environment() 获取应用环境有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40026893/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:32:51  来源:igfitidea点击:

What is difference between use env('APP_ENV'), config('app.env') or App::environment() to get app environment?

laravellaravel-5environment-variablesphpdotenv

提问by Miguel Borges

What is difference between use env('APP_ENV'), config('app.env')or App::environment()to get app environment?

是用什么区别env('APP_ENV')config('app.env')或者App::environment()导致某些应用环境?

I know that the env('APP_ENV')will to $_ENV, config('app.env')reads the configuration and App::environment()is an abstraction of all. And in my opinion the advantage is even this. Abstraction.

我知道env('APP_ENV')意志$_ENVconfig('app.env')读取配置并且App::environment()是所有的抽象。在我看来,优势甚至是这一点。抽象

I do not know if there are other differences, such as the level of performance or security

不知道有没有其他的区别,比如性能或者安全级别

回答by ndberg

In Short & up-to-date 2019:
- use env() only in config files
- use App::environment() for checking the environment (APP_ENV in .env).
- use config('app.var') for all other env variables, ex. config('app.debug')
- create own config files for your own ENV variables. Example:
In your .env:

简而言之,2019 年最新:
- 仅在配置文件中使用 env()
- 使用 App::environment() 检查环境(.env 中的 APP_ENV)。
- 将 config('app.var') 用于所有其他环境变量,例如。config('app.debug')
- 为您自己的 ENV 变量创建自己的配置文件。示例:
在您的 .env 中:

MY_VALUE=foo

example config app/myconfig.php

示例配置应用程序/myconfig.php

return [
    'myvalue' => env('MY_VALUE', 'bar'), // 'bar' is default if MY_VALUE is missing in .env
];

Access in your code:

在您的代码中访问:

config('myconfig.myvalue') // will result in 'foo'


Explanation & History:

解释和历史:

I just felt over it. When you cache your config file, env() will (sometimes?) not work right. So what I found out:

我只是觉得过去了。当您缓存配置文件时, env() 将(有时?)无法正常工作。所以我发现了什么:

  1. Laravel recommends only to use env() within the config files. Use the config() helper in your code instead of env(). For example you can call config('app.env') in your code.
  2. When you use php artisan config:cache all the configuration strings are cached by the framework and any changes you make to your .env file will not be active until you run the php artisan config:cache command again.
  1. Laravel 建议只在配置文件中使用 env() 。在您的代码中使用 config() 助手而不是 env()。例如,您可以在代码中调用 config('app.env') 。
  2. 当您使用 php artisan config:cache 时,框架会缓存所有配置字符串,并且您对 .env 文件所做的任何更改都不会生效,直到您再次运行 php artisan config:cache 命令。

From here: https://laracasts.com/discuss/channels/general-discussion/env-not-reading-variables-sometimes

从这里:https: //laracasts.com/discuss/channels/general-discussion/env-not-reading-variables-sometimes

UPDATE:
env() calls work as long as you don't use php artisan config:cache. So it's very dangerous because it will often work while development but will fail on production. See upgrade guide: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0

更新:
只要您不使用 php artisan config:cache,env() 调用就可以工作。所以这是非常危险的,因为它通常会在开发时工作,但在生产中会失败。查看升级指南:https: //laravel.com/docs/5.2/upgrade#upgrade-5.2.0

UPDATE Laravel 5.6:
Laravel now recommends in its documentationto use

更新 Laravel 5.6:
Laravel 现在在其文档中推荐使用

$environment = App::environment();

and describesthat env() is just to retrieve values from .env in config files, like config('app.env') or config('app.debug').

描述env() 只是从配置文件中的 .env 中检索值,如 config('app.env') 或 config('app.debug')。

回答by Yevgeniy Afanasyev

You have two equally good options

你有两个同样好的选择

if (\App::environment('production')) {...}

or

或者

if (app()->environment('production')) {...}

app()->environment() is actually used by Bugsnag, look in documentation hereit says

app()->environment() 实际上由Bugsnag 使用,查看文档here它说

By default, we'll automatically detect the app environment by calling the environment() function on Laravel's application instance.

默认情况下,我们会通过在 Laravel 的应用程序实例上调用 environment() 函数来自动检测应用程序环境。

Now, differences:

现在,差异:

1) env(...)function returns null after caching config. It happens on production a lot.

1)env(...)缓存配置后函数返回null。它在生产中经常发生。

2) you can change configparameters inside unit tests, it gives you flexibility while testing.

2)您可以config在单元测试中更改参数,它在测试时为您提供了灵活性。

回答by JofryHS

One thing to consider is perhaps the convenience factor of passing string to app()->environment()in order validate your current environment.

需要考虑的一件事可能是将字符串传递给以app()->environment()验证当前环境的便利因素。

// or App:: whichever you prefer.
if (app()->environment('local', 'staging')) {
    logger("We are not live yet!");
    Seeder::seedThemAll();
} else {
    logger("We are LIVE!");
}

回答by Adam Kozlowski

If you are using the config:cachecommand during deployment, you must make sure that you are only calling the envfunction from within your configuration files, and not from anywhere else in your application.

如果config:cache在部署期间使用该命令,则必须确保仅从env配置文件中调用该函数,而不是从应用程序中的任何其他位置调用该函数。

If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your envcalls to config calls.

如果您从应用程序中调用 env,强烈建议您将适当的配置值添加到配置文件中,然后从该位置调用 env,从而允许您将env调用转换为配置调用。

Add an env configuration option to your app.phpconfiguration file that looks like the following:

将 env 配置选项添加到您的app.php配置文件中,如下所示:

'env' => env('APP_ENV', 'production'),

More: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0

更多:https: //laravel.com/docs/5.2/upgrade#upgrade-5.2.0

回答by Kamil Kie?czewski

In 12factor methodologyapplication contains two types of configuration values:

12factor 方法应用程序中包含两种类型的配置值:

  • internal which not vary between deploys and are stored in laravel ./config/folder. In this type we usually store some technical optimal/good values used in application which should not be changed by users over time e.g. optimal image compression level, connection timeout, session expiration time etc.
  • external which vary between deploys and are stored in .envfile (but should not be stored in git repo, however .env.examplewith example values with detail info can be stored in repo). In this type we store usually some important/protected values which depends on local environment e.g. passwords, debug mode, db address etc.
  • internal 不会因部署而异,并存储在 laravel./config/文件夹中。在这种类型中,我们通常存储应用程序中使用的一些技术最佳/良好值,用户不应随时间更改这些值,例如最佳图像压缩级别、连接超时、会话过期时间等。
  • external 因部署而异并存储在.env文件中(但不应存储在 git repo 中,但是.env.example带有详细信息的示例值可以存储在 repo 中)。在这种类型中,我们通常存储一些重要/受保护的值,这些值取决于本地环境,例如密码、调试模式、数据库地址等。

Laravel proposes handy approach for this

Laravel 为此提出了方便的方法

  • in regular code we use only config(...)helper (so on this level programmer do not need to know which configuration value is internal and which is external)
  • in configuration code external config values should be set using env(...)helper e.g. in config/app.php 'debug' => env('APP_DEBUG', false)
  • 在常规代码中,我们只使用config(...)助手(因此在这个级别程序员不需要知道哪个配置值是内部的,哪个是外部的)
  • 在配置代码中,外部配置值应该使用env(...)helper设置,例如在 config/app.php'debug' => env('APP_DEBUG', false)