可以通过
$environment = App::environment();
var_dump($environment);
获取当前环境
默认情况下当前环境是 production
那是因为在 文件 bootstrap\start.php 中有
设置:
homestead 就是指计算机的名字 ,linux 或者mac可以使用hostname 查看,
windows可以在powershell下使用hostname或者在计算机属性中查看 你的计算机名字一般不会是
homestead 所以找不到这个名字就会返回是production 即当前的默认环境
我们可以简要分析一下 首先分析 函数detectEnvironment()
设置:
$env = $app->detectEnvironment(array(
'local' => array('homestead'),
));
homestead 就是指计算机的名字 ,linux 或者mac可以使用hostname 查看,
windows可以在powershell下使用hostname或者在计算机属性中查看 你的计算机名字一般不会是
homestead 所以找不到这个名字就会返回是production 即当前的默认环境
定义在vendor\laravel\framework\src\Illuminate\Foundation\Application.php 中
public function detectEnvironment($envs)
{
$args = isset($_SERVER['argv']) ? $_SERVER['argv'] : null;
return $this['env'] = (new EnvironmentDetector())->detect($envs, $args);
}
继续分析 detect() 函数
定义在vendor\laravel\framework\src\Illuminate\Foundation\EnvironmentDetector.php 中
public function detect($environments, $consoleArgs = null)
{
if ($consoleArgs)
{
return $this->detectConsoleEnvironment($environments, $consoleArgs);
}
else
{
return $this->detectWebEnvironment($environments);
}
}
默认 $consoleArgs 为null 那么接着分析 函数detectWebEnvironment()
protected function detectWebEnvironment($environments)
{
// If the given environment is just a Closure, we will defer the environment check
// to the Closure the developer has provided, which allows them to totally swap
// the webs environment detection logic with their own custom Closure's code.
if ($environments instanceof Closure)
{
return call_user_func($environments);
}
foreach ($environments as $environment => $hosts)
{
// To determine the current environment, we'll simply iterate through the possible
// environments and look for the host that matches the host for this request we
// are currently processing here, then return back these environment's names.
foreach ((array) $hosts as $host)
{
if ($this->isMachine($host)) return $environment;
}
}
return 'production';
}
可见最后renturn 'production'; 由此 可以知道为什么返回 production了
那么我们只需要把 'local' => array('homestead'), 中的homestead 改成我们自己的计算机名字就会是当前环境变成local
你也可以命名其他环境。
这样你就可以把许多配置写到自己的文件夹下面了
例如 app/config 文件夹
这个时候很多配置当当前环境例如是local 没有的时候使用的默认的配置文件例如
cache.php
但是你也可以直接在config/local 下面创建cache.php 覆盖默认的环境配置
使用不同环境另一个一个作用是 敏感信息的保护
这个作用可以查看官方文档,我这里就不 复制粘贴了。