在Laravel 5中设置ENV变量的正确方法是什么?

时间:2022-10-18 17:43:06

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:

他们也排除了。env。* gitignore,现在有:

.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.:

那么,如果我有两个以上的环境,我是否必须现在将它们全部设置为一个.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将如何知道我正在使用的环境?

5 个解决方案

#1


29  

You can do it exactly the same as in Laravel 4:

你可以像拉腊威尔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

当然本地环境是本地环境,您可以将其转换为生产环境或开发环境

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文件你可以modfiy:

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.

从主env文件加载基于APP_ENV的额外env文件。

Now you will be able to use it in your other configuration file as always: $_ENV['MY_DB']

现在您可以在其他配置文件中使用它:$_ENV['MY_DB']

#2


12  

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.

在引导/ app.php。

//edit Soo.. after digging into this for the past hour I might as well add some additional info here:

/ /编辑秀. .在深入研究这个问题一小时后,我不妨在这里补充一些额外的信息:

  • Laravel uses .env files for configuration
  • Laravel使用.env文件进行配置。
  • By default, the file ".env" in the root directory of the application is loaded
  • 默认情况下,文件。在应用程序的根目录中载入env
  • You can access the values within those .env files via the env() helper function or directly via PHP's native getenv() function. Although you should only do so to fill your config files (see /config/*.php), because those can be cached.
  • 您可以通过env()帮助函数或直接通过PHP的本机getenv()函数访问这些.env文件中的值。尽管您应该只填充配置文件(请参见/config/*.php),因为这些文件可以缓存。
  • the .env files are loaded in the DetectEnvironment class. I found this helpful while debugging to set breakpoints. Please take note of the line (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();: Since it uses load() any environment value that has already been set will not be overwritten! (You would have to use overload() to do so - this drove me nuts because homestead sets the APP_ENV variable to local in the php-fpm config /etc/php/7.0/fpm/php-fpm.conf and you cannot change it via .env file)
  • env文件在DetectEnvironment类中被加载。在调试设置断点时,我发现这很有用。请注意这条线(新Dotenv($app->环境路径(),$app->环境文件())->load();:因为它使用load()已经设置的任何环境值都不会被覆盖!(您将不得不使用重载()这样做——这让我抓狂,因为homestead将APP_ENV变量设置为php-fpm配置/etc/php/7.0/fpm/php-fpm。conf不能通过。env文件改变
  • when writing unit tests, you usually inherit from TestCase, which sets the APP_ENV variable to testing (via refreshApplication() -- using putenv() to override the default local value)
  • 在编写单元测试时,通常会继承TestCase,它将APP_ENV变量设置为测试(通过refreshApplication()——使用putenv()来覆盖默认的本地值)

#3


5  

You can check on how to setup properly. How to Setup Multiple Environment for Laravel 5 Developers Way

您可以检查如何正确设置。如何为Laravel 5开发者设置多个环境?

Based on Marcin Nabiałek, I removed some part of it, and put it in proper file to load it right.

基于戈Nabiałek,我删除了一些部分,并把它放在适当的文件加载。

#4


1  

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贡献我的解决方案,这是稍微简单一点的IMHO。在引导/应用程序。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.

这是所有。

#5


0  

The fact that you can't have more than one .env file by default and that 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文件不应该在版本控制中,应该根据环境配置。

So, if i have more than 2 environments, do i have to set all of them in a single .env file now?

那么,如果我有两个以上的环境,我需要把它们都设置成一个。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个服务器错误。

#1


29  

You can do it exactly the same as in Laravel 4:

你可以像拉腊威尔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

当然本地环境是本地环境,您可以将其转换为生产环境或开发环境

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文件你可以modfiy:

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.

从主env文件加载基于APP_ENV的额外env文件。

Now you will be able to use it in your other configuration file as always: $_ENV['MY_DB']

现在您可以在其他配置文件中使用它:$_ENV['MY_DB']

#2


12  

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.

在引导/ app.php。

//edit Soo.. after digging into this for the past hour I might as well add some additional info here:

/ /编辑秀. .在深入研究这个问题一小时后,我不妨在这里补充一些额外的信息:

  • Laravel uses .env files for configuration
  • Laravel使用.env文件进行配置。
  • By default, the file ".env" in the root directory of the application is loaded
  • 默认情况下,文件。在应用程序的根目录中载入env
  • You can access the values within those .env files via the env() helper function or directly via PHP's native getenv() function. Although you should only do so to fill your config files (see /config/*.php), because those can be cached.
  • 您可以通过env()帮助函数或直接通过PHP的本机getenv()函数访问这些.env文件中的值。尽管您应该只填充配置文件(请参见/config/*.php),因为这些文件可以缓存。
  • the .env files are loaded in the DetectEnvironment class. I found this helpful while debugging to set breakpoints. Please take note of the line (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();: Since it uses load() any environment value that has already been set will not be overwritten! (You would have to use overload() to do so - this drove me nuts because homestead sets the APP_ENV variable to local in the php-fpm config /etc/php/7.0/fpm/php-fpm.conf and you cannot change it via .env file)
  • env文件在DetectEnvironment类中被加载。在调试设置断点时,我发现这很有用。请注意这条线(新Dotenv($app->环境路径(),$app->环境文件())->load();:因为它使用load()已经设置的任何环境值都不会被覆盖!(您将不得不使用重载()这样做——这让我抓狂,因为homestead将APP_ENV变量设置为php-fpm配置/etc/php/7.0/fpm/php-fpm。conf不能通过。env文件改变
  • when writing unit tests, you usually inherit from TestCase, which sets the APP_ENV variable to testing (via refreshApplication() -- using putenv() to override the default local value)
  • 在编写单元测试时,通常会继承TestCase,它将APP_ENV变量设置为测试(通过refreshApplication()——使用putenv()来覆盖默认的本地值)

#3


5  

You can check on how to setup properly. How to Setup Multiple Environment for Laravel 5 Developers Way

您可以检查如何正确设置。如何为Laravel 5开发者设置多个环境?

Based on Marcin Nabiałek, I removed some part of it, and put it in proper file to load it right.

基于戈Nabiałek,我删除了一些部分,并把它放在适当的文件加载。

#4


1  

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贡献我的解决方案,这是稍微简单一点的IMHO。在引导/应用程序。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.

这是所有。

#5


0  

The fact that you can't have more than one .env file by default and that 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文件不应该在版本控制中,应该根据环境配置。

So, if i have more than 2 environments, do i have to set all of them in a single .env file now?

那么,如果我有两个以上的环境,我需要把它们都设置成一个。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个服务器错误。