背景:实现$bootstrappers中的LoadEnvirenmentVariables,非cli模式
bootstrap()
//class Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables
public function bootstrap(Application $app)
{
//$app->environmentPath()='root_path',$app->environmentFile()='.env'
(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
}
初始化Dotenv并执行load()
public function __construct($path, $file = '.env')
{
$this->filePath = $this->getFilePath($path, $file);
$this->loader = new Loader($this->filePath, true);
}
public function load()
{
return $this->loadData();
}
protected function loadData($overload = false)
{
// setImmutable设定了$loader->immutable=ture
return $this->loader->setImmutable(!$overload)->load();
}
将.env配置文件中的设定添加到超全局变量ENV,SERVER中
public function load()
{
$this->ensureFileIsReadable();//校验.env文件是否可读
$filePath = $this->filePath;
$lines = $this->readLinesFromFile($filePath);//通过file()以行为单位读取内容
foreach ($lines as $line) {
//校验不存在注释“#”且存在“=”则进行环境变量设置
if (!$this->isComment($line) && $this->looksLikeSetter($line)) {
$this->setEnvironmentVariable($line);
}
}
return $lines;
}
setEnvironmentVariable()
public function setEnvironmentVariable($name, $value = null)
{
//获取$file内容截取并过滤,分别赋值给$name,$value
list($name, $value) = $this->normaliseEnvironmentVariable($name, $value);
$this->variableNames[] = $name;
//对已经设置过的环境变量不进行覆盖
if ($this->immutable && $this->getEnvironmentVariable($name) !== null) {
return;
}
//对apache设定的环境变量进行覆盖
if (function_exists('apache_getenv') && function_exists('apache_setenv') && apache_getenv($name) !== false) {
apache_setenv($name, $value);
}
//将env信息添加到getenv()中
if (function_exists('putenv')) {
putenv("$name=$value");
}
//将env信息添加到$_ENV与$_SERVER
$_ENV[$name] = $value;
$_SERVER[$name] = $value;
}