这就是我设置环境的方式:
在您的应用程序的根目录中创建一个.environment 文件并定义您的环境并向其中添加您的敏感信息:
<?php
return array(
'APPLICATION_ENV' => 'development', /// this is where you will set your environment
'DB_HOST' => 'localhost',
'DB_DATABASE_NAME' => 'laraveldatabase',
'DB_DATABASE_USER' => 'laraveluser',
'DB_DATABASE_PASSWORD' => '!Bassw0rT',
);
将其添加到您的 .gitignore 文件中,这样您就不会冒险将密码发送到 Github 或您的任何其他服务器。
就在$app->detectEnvironment 之前,在文件bootstrap/start.php 中,将您的.environment 文件加载到PHP 环境中:
foreach(require __DIR__.'/../.environment' as $key => $value)
{
putenv(sprintf('%s=%s', $key, $value));
}
然后你只需要使用它:
$env = $app->detectEnvironment(function () {
return getenv('APPLICATION_ENV'); // your environment name is in that file!
});
它可以在任何地方工作,因此您不再需要单独的开发和生产目录:
<?php
return array(
'connections' => array(
'postgresql' => array(
'driver' => 'pgsql',
'host' => getenv('DB_HOST'),
'database' => getenv('DB_DATABASE_NAME'),
'username' => getenv('DB_DATABASE_USER'),
'password' => getenv('DB_DATABASE_PASSWORD'),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
),
);
请注意,我没有设置后备:
return getenv('APPLICATION_ENV') ?: 'local';
因为,如果我不设置文件,我希望它在我将应用程序部署到的每台服务器上都失败。
Laravel 利用了类似的东西,您在应用程序的根目录中创建 .env 文件:
.env.local.php // this file will appear only in your local environment, not in production
.env.staging.php // for staging
.env.php // for production
在这些文件中添加您的敏感信息
<?php
return array(
'DB_HOST' => 'localhost',
'DB_USER' => 'root',
'DB_PASS' => '1023809182root@pass',
);
创建按环境分隔的文件:
app/config/local/database.php
应用程序/config/staging/database.php
app/config/database.php
然后在您的文件或应用程序的任何位置,您可以通过 $_ENV 或 getenv() 访问您的敏感数据:
$_ENV['DB_HOST']
$_ENV['DB_USER']
$_ENV['DB_PASS']
例子:
'postgresql' => [
'driver' => 'pgsql',
'host' => 'localhost',
'database' => getenv('DB_HOST'),
'username' => getenv('DB_USER'),
'password' => getenv('DB_PASS'),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
],
但您仍然需要设置环境名称,这可能是您的问题。
不要忘记将这些文件添加到您的 .gitignore 文件中,这样您就不会冒险将它们发送到您的 github。
文档:http://laravel.com/docs/configuration#protecting-sensitive-configuration