php Laravel 中的环境驱动数据库设置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13860283/
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
Environment driven database settings in Laravel?
提问by Hailwood
I am moving over the the Laravel framework, but I am having trouble with the database settings,
我正在使用 Laravel 框架,但是我在数据库设置方面遇到了问题,
Specifically, I have my environments setup, and they are working fine for the application.php config file, however the database.php config file seems to have no effect.
具体来说,我有我的环境设置,它们对 application.php 配置文件工作正常,但是 database.php 配置文件似乎没有效果。
Even if I have a database.php config file in my environments folder it is never loaded, I put a bunch of invalid characters (keyboard mash) into the file to get php to throw an error, but it is never hit.
即使我的环境文件夹中有一个 database.php 配置文件,它也永远不会加载,我将一堆无效字符(键盘混搭)放入文件中以使 php 抛出错误,但它永远不会被命中。
Does Laravel not support environment based database settings? or am I doing this wrong?
Laravel 不支持基于环境的数据库设置吗?还是我做错了?
回答by Laurence
You can definitely set database settings (and any other config setting) by environment.
您绝对可以按环境设置数据库设置(和任何其他配置设置)。
For Laravel 3 (for Laravel 4 and Laravel 5 see below):
对于 Laravel 3(对于 Laravel 4 和 Laravel 5,见下文):
Firstly - you need to define $environmentsin your paths.phpand set it to something like this:
首先 - 你需要$environments在你的中定义paths.php并将其设置为这样的:
$environments = array(
'development' => array('*.dev'),
'production' => array('*.com'),
);
Laravel will automaticallylook for this variable, and if set, will use the associated configuration.
Laravel 会自动寻找这个变量,如果设置了,就会使用相关的配置。
Normally you have a configfolder, with settings such as database.phpand auth.php
通常,您有一个config文件夹,其中包含诸如database.php和auth.php
Now just create a new folder for each Laravel_Envyou plan to use (such as Development). You'll end up with a folder structure like this;
现在只需为Laravel_Env您计划使用的每个文件夹(例如 Development)创建一个新文件夹。你最终会得到这样的文件夹结构;
/application
/config
/development
database.php
/production
database.php
application.php
config.php
database.php
...
user_agents.php
You'll note I've only included database.phpin each subfolder. Laravel will always load the default config settings first, then override them with any custom configs from the environments setting.
你会注意到我只包含database.php在每个子文件夹中。Laravel 将始终首先加载默认配置设置,然后使用环境设置中的任何自定义配置覆盖它们。
Finally, in your development/database file, you would have something like this;
最后,在你的开发/数据库文件中,你会有这样的东西;
<?php
return array(
'default' => 'mysql'
);
p.s. I just tested this on the current 3.2.12 build of Laravel - and it definitely works.
ps 我刚刚在 Laravel 的当前 3.2.12 版本上测试了这个 - 它绝对有效。
Bonus Tip:You can also automatically set an environment for Artisan, so you do not have to include the environment manually on each command line! To do this:
额外提示:您还可以为 Artisan 自动设置环境,因此您不必在每个命令行中手动包含环境!去做这个:
You need to know your 'hostname' that you are running Artisan on. To find out - temporarily edit the
artisan.phpin your root folder, and addvar_dump(gethostname());to line 2 (i.e. above everything).Run
php artisanfrom the command line. You will get a string dump with your hostname. In my case its "TSE-Win7";Remove the changes to the
artisan.phpfileAdd your hostname (i.e. "TSE-Win7") to the environments.
您需要知道运行 Artisan 的“主机名”。找出 - 临时编辑
artisan.php根文件夹中的 ,并添加var_dump(gethostname());到第 2 行(即高于所有内容)。运行
php artisan命令行。您将获得带有主机名的字符串转储。就我而言,它是“TSE-Win7”;删除对
artisan.php文件的更改将您的主机名(即“TSE-Win7”)添加到环境中。
You should end up with something like this:
你应该得到这样的结果:
$environments = array(
'development' => array('*.dev', 'TSE-Win7'),
'production' => array('*.com'),
);
Artisan will now run using your development environment. If you deploy to a live server - re-run these steps to get the hostname() for the server, and you can configure a specific artisan config just for the server!
Artisan 现在将使用您的开发环境运行。如果您部署到实时服务器 - 重新运行这些步骤以获取服务器的主机名(),并且您可以仅为服务器配置特定的工匠配置!
For Laravel 4:
对于 Laravel 4:
The default environment is always production. But in your start.phpfile you can define additional environments.
默认环境始终为production. 但是在start.php文件中,您可以定义其他环境。
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),
));
On Linux and Mac, you may determine your hostnameby type hostnamein your terminal - it will output the name of your computer. On Windows put dd(gethostname());at the beginning of your routes.phpfile - and run the website once - it will show you the current hostname of your computer.
在 Linux 和 Mac 上,您可以hostname通过hostname终端中的类型来确定您的类型- 它会输出您的计算机名称。在 Windows 上放在文件dd(gethostname());的开头routes.php- 并运行一次网站 - 它会显示您计算机的当前主机名。
To get the current environment as a variable in your application- read this SO answer here. Laravel 4: how can I get the environment value?
要将当前环境作为应用程序中的变量- 请在此处阅读此 SO 答案。Laravel 4:如何获得环境值?
For Laravel 5:
对于 Laravel 5:
There is single configuration file, called .envin your root directory.
Watch this laracast, config explained fully.
有一个配置文件,.env在您的根目录中调用。
观看这个 laracast,充分解释了配置。
回答by Knight
if you are using the artisan ( command line for laravel ) every command you need to add
如果您使用的是工匠(laravel 的命令行),您需要添加的每个命令
artisan bla bla bla --env=Development
or
或者
artisan bla bla bla --env=Production
回答by Faiyaz Haider
Heres how I have it setup for my needs.
下面是我如何根据我的需要设置它。
I personally need 4 different configurations:
我个人需要 4 种不同的配置:
- localhost (Mac OSX) - /Library/WebServer/Documents/www/my-domain.com/development/
- dev.my-domain.com (VPS) - /var/www/my-domain.com/development/
- test.my-domain.com (VPS) - /var/www/my-domain.com/test/
- my-domain.com (VPS) - /var/www/my-domain.com/web/
- 本地主机 (Mac OSX) - /Library/WebServer/Documents/www/my-domain.com/development/
- dev.my-domain.com (VPS) - /var/www/my-domain.com/development/
- test.my-domain.com (VPS) - /var/www/my-domain.com/test/
- my-domain.com (VPS) - /var/www/my-domain.com/web/
Since all 4 of my environments have distinctive directory structure, I can use php's magic constant __DIR__to fetch the app directory and then use the strpos()function to do a simple check and return the appropriate environment. It will take care of Artisan environment as well, no need to manually type the environment, or add any machine names.
由于我的所有 4 个环境都有独特的目录结构,我可以使用 php 的魔术常量__DIR__来获取应用程序目录,然后使用strpos()函数进行简单检查并返回适当的环境。它也会处理 Artisan 环境,无需手动输入环境或添加任何机器名称。
Inside the
在 - 的里面
bootstrap/start.php
引导程序/start.php
Add a callback function
添加回调函数
$env = $app->detectEnvironment(function(){
$haystack = __DIR__; // Catch the directory path
// Set the booleans (remove the first '/', else strpos() will return 0)
$isLocal = strpos($haystack, 'Library/WebServer/Documents/www/my-domain.com/development/');
$isDevelopment = strpos($haystack, 'var/www/my-domain.com/development/');
$isTest = strpos($haystack, 'var/www/my-domain.com/test/');
$isProduction = strpos($haystack, 'var/www/my-domain.com/web/');
// Set the environments
if ($isLocal) $environment = "local";
if ($isDevelopment) $environment = "development";
if ($isTest) $environment = "test";
if ($isProduction) $environment = "production";
// Return the appropriate environment
return $environment
});
Another alternative
另一种选择
We can also set and grab all the values at once into an array, and run a foreach loop.
我们还可以一次设置所有值并将其抓取到一个数组中,然后运行 foreach 循环。
Tip:Since we using the strpos()function, which checks position of the first occurrence of the given value against the $haystack, and returns the position number. We don't really have to supply the entire path, we can simply add a distinctive value from each path to get the job done.
提示:由于我们使用了strpos()函数,它会根据$haystack检查给定值第一次出现的位置,并返回位置编号。我们真的不必提供整个路径,我们可以简单地从每个路径添加一个独特的值来完成工作。
// Check the boolean, if true set to given value, else set NULL
$environments[] = strpos($haystack, "Library") ? 'local' : NULL;
$environments[] = strpos($haystack, "develop") ? 'development': NULL;
$environments[] = strpos($haystack, "test") ? 'test' : NULL;
$environments[] = strpos($haystack, "web") ? 'production' : NULL;
// Loop through each, if not null then we have our environment
foreach ($environments as $environment) {
if(!is_null($environment))
return $environment;
}
Whether we work on one machine or multiple, the chances of having the same path to different environments is very slim.
无论我们在一台机器上工作还是在多台机器上工作,以相同的路径进入不同环境的机会都非常渺茫。
Or so I think. :)
或者我认为是这样。:)
回答by Troy Harvey
Laravel 5
Laravel 5
Use the DotEnvapproach detailed in the Laravel docs here.
使用此处 Laravel 文档中详述的DotEnv方法。
Laravel 4
Laravel 4
We are using the method Jeffrey Way recommended in this Laracasts lesson.
我们正在使用本Laracasts 课程中Jeffrey Way 推荐的方法。
Create
configdirectories for each environment./app /config /local database.php /production database.phpSet an environment variable on your production server. Google for the best approach on your production platform. For example, here are great suggestions for Ubuntu, Dreamhost, and Heroku. We added a single line to
/etc/environment:ENV=productionAdd this closure to
/bootstrap/start.php. With this setup, any server missing theENVenvironment variable will default to thelocalenvironment config.$env = $app->detectEnvironment( function () { return getenv('ENV') ? : 'local'; } );
为每个环境创建
config目录。/app /config /local database.php /production database.php在您的生产服务器上设置环境变量。谷歌为您的生产平台提供最佳方法。例如,这里为Ubuntu、Dreamhost和Heroku提供了很好的建议。我们添加了一行
/etc/environment:ENV=production将此闭包添加到
/bootstrap/start.php. 使用此设置,任何缺少ENV环境变量的服务器都将默认使用local环境配置。$env = $app->detectEnvironment( function () { return getenv('ENV') ? : 'local'; } );
回答by Justin
How to setup environment specific configurationis now in the official Laravel docs. I would recommend using their method instead of the accepted answer:
如何设置环境特定的配置现在在官方 Laravel 文档中。我建议使用他们的方法而不是接受的答案:
It is often helpful to have different configuration values based on the environment the application is running in. For example, you may wish to use a different cache driver on your local development machine than on the production server. It is easy to accomplish this using environment based configuration.
Simply create a folder within the config directory that matches your environment name, such as local. Next, create the configuration files you wish to override and specify the options for that environment. For example, to override the cache driver for the local environment, you would create a cache.php file in app/config/local with the following content:
根据应用程序运行的环境使用不同的配置值通常很有帮助。例如,您可能希望在本地开发机器上使用与生产服务器上不同的缓存驱动程序。使用基于环境的配置很容易实现这一点。
只需在 config 目录中创建一个与您的环境名称匹配的文件夹,例如 local。接下来,创建您希望覆盖的配置文件并为该环境指定选项。例如,要覆盖本地环境的缓存驱动程序,您将在 app/config/local 中创建一个包含以下内容的 cache.php 文件:
<?php
return array(
'driver' => 'file',
);
Note: Do not use 'testing' as an environment name. This is reserved for unit testing. Notice that you do not have to specify every option that is in the base configuration file, but only the options you wish to override. The environment configuration files will "cascade" over the base files.
Next, we need to instruct the framework how to determine which environment it is running in. The default environment is always production. However, you may setup other environments within the bootstrap/start.php file at the root of your installation. In this file you will find an $app->detectEnvironment call. The array passed to this method is used to determine the current environment. You may add other environments and machine names to the array as needed.
注意:不要使用“testing”作为环境名称。这是为单元测试保留的。请注意,您不必指定基本配置文件中的每个选项,而只需指定您希望覆盖的选项。环境配置文件将“层叠”在基本文件上。
接下来,我们需要指示框架如何确定它运行在哪个环境中。默认环境始终是生产环境。但是,您可以在安装根目录的 bootstrap/start.php 文件中设置其他环境。在这个文件中,你会发现一个 $app->detectEnvironment 调用。传递给此方法的数组用于确定当前环境。您可以根据需要向阵列添加其他环境和机器名称。
<?php
$env = $app->detectEnvironment(array(
'local' => array('your-machine-name'),
));
In this example, 'local' is the name of the environment and 'your-machine-name' is the hostname of your server. On Linux and Mac, you may determine your hostname using the hostname terminal command.
If you need more flexible environment detection, you may pass a Closure to the detectEnvironment method, allowing you to implement environment detection however you wish:
在此示例中,“local”是环境名称,“your-machine-name”是服务器的主机名。在 Linux 和 Mac 上,您可以使用 hostname 终端命令确定您的主机名。
如果您需要更灵活的环境检测,您可以将 Closure 传递给 detectEnvironment 方法,允许您根据需要实现环境检测:
$env = $app->detectEnvironment(function()
{
$domain = explode('.', $_SERVER['HTTP_HOST']);
switch($domain[0])
{
case 'localhost':
case 'localhost:8080':
case 'dev':
return 'development';
break;
case 'mysite':
default:
return 'production';
break;
}
});
You may access the current application environment via the environment method:
Accessing The Current Application Environment
您可以通过 environment 方法访问当前的应用程序环境:
访问当前应用环境
$environment = App::environment();
You may also pass arguments to the environment method to check if the environment matches a given value:
您还可以将参数传递给 environment 方法以检查环境是否与给定值匹配:
if (App::environment('local'))
{
// The environment is local
}
if (App::environment('local', 'staging'))
{
// The environment is either local OR staging...
}
回答by Schneidey
I've been working away on this today, struggling to work out how best to do environmental settings for a database. In the end, after trying several methods, I fully agree with @troy-harvey that Jeffrey Way's recommendation of doing this is the best (for me at least). One thing I will add to this, and its what held me up so much today is (and correct me if I'm wrong) that you need to access the settings you are trying to over-ride in your environmental settings file by their corresponding array keys. I started out returning a simple array:
我今天一直在努力解决这个问题,努力找出如何最好地为数据库进行环境设置。最后,在尝试了几种方法之后,我完全同意@troy-harvey 的观点,Jeffrey Way 建议这样做是最好的(至少对我而言)。我要添加的一件事是,今天让我如此受挫的是(如果我错了,请纠正我),您需要通过相应的设置访问您试图在环境设置文件中覆盖的设置数组键。我开始返回一个简单的数组:
return [
'database' => '<db_name>',
'username' => '<db_user>',
'password' => '<db_pass>',
];
within an app/config/staging/database.php. This had no effect and after much head scratching realised that you need to access the array as it is presented in app/config/database.php, like so:
在一个app/config/staging/database.php. 这没有任何效果,经过多次摸索后意识到您需要访问 中显示的数组app/config/database.php,如下所示:
<?php
return [
'connections' => [
'mysql' => [
'database' => '<db_name>',
'username' => '<db_user>',
'password' => '<db_pass>'
]
]
];
At least this is how I finally managed to get my settings being picked up.
至少这是我最终设法让我的设置被接受的方式。
Adding this here in case anyone else is struggling to work this out. Upon realisation I understood how obvious a mistake I was making.
在这里添加这个以防其他人正在努力解决这个问题。意识到这一点后,我明白我犯了一个多么明显的错误。
Edited 01 July 2014
2014 年 7 月 1 日编辑
An additional comment to this is that since 4.1 Laravel ships with an append_config() helper function for appending environmental configurations to the main config array.
对此的附加评论是,自 4.1 Laravel 附带一个 append_config() 辅助函数,用于将环境配置附加到主配置数组。
This would look like this for the example given above:
对于上面给出的示例,这看起来像这样:
<?php
return append_config([
'connections' => [
'mysql' => [
'database' => '<db_name>',
'username' => '<db_user>',
'password' => '<db_pass>'
]
]
]);
回答by Robert Brisita
In Laravel 3 to detect the environment it was:
在 Laravel 3 中检测环境是:
Request:env()
Which would return whatever was identified in the environments array found in the paths.php file.
这将返回在paths.php 文件中找到的环境数组中标识的任何内容。
As mentioned before in Laravel 4 it is now:
正如之前在 Laravel 4 中提到的,它现在是:
App:: environment()
回答by Abi Xalmon
My way of doing it!
我的做法!
$env = $app->detectEnvironment( function() {
if ( file_exists('../.env.local.php') ) {
return 'local';
}
if ( file_exists('../.env.beta.php') ) {
return 'beta';
}
return 'production';
} );
回答by Phil Pearce
If you're trying to use Laravel in a Windows environment, check out the settings in file .env in the top level folder for your Laravel project - these will override whatever database settings you have in config/database.php
如果您尝试在 Windows 环境中使用 Laravel,请查看 Laravel 项目顶级文件夹中的 .env 文件中的设置 - 这些将覆盖您在 config/database.php 中的任何数据库设置
回答by Mwirabua Tim
If you are on Laravel 4 here is a gistthat will take you through the process step by step. Credits to @"The Shift Exchange"'s answer for guiding me to create it.
如果您使用的是 Laravel 4,这里有一个要点,将带您逐步完成整个过程。感谢@“The Shift Exchange”指导我创建它的答案。

