Laravel 5-通过服务器名称进行环境检测 [英] Laravel 5 - Environment Detection by Server Name

查看:98
本文介绍了Laravel 5-通过服务器名称进行环境检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解Laravel 5,它使用.env文件,因此我们可以设置特定的环境值.

I understand with Laravel 5, it uses .env files so we can set specific enivornment values.

我的问题是,Laravel 5中有没有办法举例说明,

My question is, is there a way in Laravel 5, to say for example,

if ($SERVER_NAME == "my_production_server") {
    $environment = "production"
}

然后,它使用生产价值.我的想法是,我希望将所有环境及其变量放置在一个文件或目录中,或任何其他方式,以便我们无需任何人工干预即可部署整个构建,并将其全部检查到代码存储库中.

And from that it uses production values. My thinking is, I'd like all the environments and their variables placed in one file or directory, or whatever so we can deploy the whole build without any manual intervention, and we can check this all into our code repository.

推荐答案

Laravel 5比以前更难了,但是这是解决问题的方法. 完成此操作后,只需更改.env文件的值,环境就会更改

Laravel 5 has made this a little harder than before but here's the way to do it. All you will need to do after this is change a value of your .env file and the environment will change

执行此操作的步骤如下

  1. 查看由Laravel安装的本地.env,并将其内容更改为 local production 或您需要的其他任何内容

  1. Look at your local .env installed by Laravel and change its contents to local or production or whatever else you need

创建2个文件.local.env.production.env

添加默认环境值:

  • .local.env中:APP_ENV=local
  • .production.env中:APP_ENV=production
  • In .local.env : APP_ENV=local
  • In .production.env : APP_ENV=production

创建一个新的php文件并将其命名为environment.php,将其保存到以下文件夹中:app/bootstrap/environment.php

Create new php file and named it, environment.php, save it into this folder: app/bootstrap/environment.php

$env = $app->detectEnvironment(function(){
  $environmentPath = __DIR__.'/../.env';
   $setEnv = trim(file_get_contents($environmentPath));
   if (file_exists($environmentPath)){
          putenv("APP_ENV=$setEnv");
          if (getenv('APP_ENV') && file_exists(__DIR__.'/../.' .getenv('APP_ENV') .'.env')) {
               Dotenv::load(__DIR__ . '/../', '.' . getenv('APP_ENV') . '.env');
          } 
   }
});

  • 在引导文件中包含您的environment.php文件.将其粘贴到您的bootstrap/app.php文件中.

  • Include your environment.php file in bootstrap file. Paste it inside your bootstrap/app.php file.

    require __DIR__.'/environment.php';
    

  • 是的!你完成了.

    注意::如果Laravel找不到.env文件,它将自动使用.production.env,这对部署非常有用

    NOTE: If Laravel can't find a .env file it automatically uses .production.env which makes it awesome for deployments

    贷方 查看全文

    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆