laravel .env环境变量原理

devtools/2024/10/21 18:02:24/

介绍

对于应用程序运行的环境来说,不同的环境有不同的配置通常是很有用的。Laravel 利用 Vance Lucas 的 PHP 库 DotEnv 使得此项功能的实现变得非常简单。当应用程序收到请求时,.env 文件中列出的所有变量将被加载到 PHP 的超级全局变量 $_ENV 中。

使用

你可以使用 env 函数检索这些变量的值。事实上,如果你查看 Laravel 的配置文件,你就能注意到有数个选项已经使用了这个函数:

php">'debug' => env('APP_DEBUG', false),

传递给 env 函数的第二个值是「默认值」。如果给定的键不存在环境变量,则会使用该值。

使用分析

我们可以先看一下助手函数 env

php">if (! function_exists('env')) {/*** Gets the value of an environment variable.** @param  string  $key* @param  mixed  $default* @return mixed*/function env($key, $default = null){return Env::get($key, $default);}
}

ENV::get 最终追踪到 EnvConstAdapter get

php">    /*** Get an environment variable, if it exists.** @param string $name** @return \PhpOption\Option*/public function get($name){if (array_key_exists($name, $_ENV)) {return Some::create($_ENV[$name]);}return None::create();}

读取$_ENV内容,$_ENV是 通过环境提供给脚本的变量

php">/*** @xglobal $_ENV array** Variables provided to the script via the environment.* Analogous to the old $HTTP_ENV_VARS array (which is still available, but deprecated).** <p><a href="https://secure.php.net/manual/en/reserved.variables.php">* https://secure.php.net/manual/en/reserved.variables.php</a>*/
$_ENV = array();

写入$_ENV

bootstrap/app.php

php">    try {(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(dirname(__DIR__)))->bootstrap();} catch (Dotenv\Exception\InvalidPathException $e) {//}

Laravel\Lumen\Bootstrap\LoadEnvironmentVariables 中

php"><?phpnamespace Laravel\Lumen\Bootstrap;use Dotenv\Dotenv;
use Dotenv\Exception\InvalidFileException;
use Illuminate\Support\Env;
use Symfony\Component\Console\Output\ConsoleOutput;class LoadEnvironmentVariables
{/*** The directory containing the environment file.** @var string*/protected $filePath;/*** The name of the environment file.** @var string|null*/protected $fileName;/*** Create a new loads environment variables instance.** @param  string  $path* @param  string|null  $name* @return void*/public function __construct($path, $name = null){$this->filePath = $path;$this->fileName = $name;}/*** Setup the environment variables.** If no environment file exists, we continue silently.** @return void*/public function bootstrap(){try {$this->createDotenv()->safeLoad();} catch (InvalidFileException $e) {$this->writeErrorAndDie(['The environment file is invalid!',$e->getMessage(),]);}}/*** Create a Dotenv instance.** @return \Dotenv\Dotenv*/protected function createDotenv(){return Dotenv::create($this->filePath,$this->fileName,Env::getFactory());}/*** Write the error information to the screen and exit.** @param  string[]  $errors* @return void*/protected function writeErrorAndDie(array $errors){$output = (new ConsoleOutput)->getErrorOutput();foreach ($errors as $error) {$output->writeln($error);}die(1);}
}

我们可以看到 bootstrap方法是创建Dotenv实例,并且调用Dotenv实例的safeload方法,Dotenv::create参数的含义

   $this->filePath, #env所在目录$this->fileName, #env名称,默认 .envEnv::getFactory() #laravel env相关的适配器工厂

由此我们可以自定义.env的位置和名称

safeload方法

php">    /*** Load environment file in given directory.** @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException** @return array<string|null>*/public function load(){return $this->loadData();}/*** Load environment file in given directory, silently failing if it doesn't exist.** @throws \Dotenv\Exception\InvalidFileException** @return array<string|null>*/public function safeLoad(){try {return $this->loadData();} catch (InvalidPathException $e) {// suppressing exceptionreturn [];}}/*** Load environment file in given directory.** @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException** @return array<string|null>*/public function overload(){return $this->loadData(true);}/*** Actually load the data.** @param bool $overload** @throws \Dotenv\Exception\InvalidPathException|\Dotenv\Exception\InvalidFileException** @return array<string|null>*/protected function loadData($overload = false){return $this->loader->setImmutable(!$overload)->load();}

根据代码分析,safeLoad 中使用了 try {} catuch {} 捕获了异常,不会因为地址错误而报错,同时加载loadData,这里默认使用了loadData = true, 影响的Dotenv 创建的 DotenvVariables(array $adapters, $immutable)实例属性 $immutable值。我们通过追踪load方法,最终可以找到该方法:

php">    /*** Set an environment variable.** @param string      $name* @param string|null $value** @throws \InvalidArgumentException** @return void*/public function set($name, $value = null){if (!is_string($name)) {throw new InvalidArgumentException('Expected name to be a string.');}// Don't overwrite existing environment variables if we're immutable// Ruby's dotenv does this with `ENV[key] ||= value`.if ($this->isImmutable() && $this->get($name) !== null && $this->loaded->get($name)->isEmpty()) {return;}$this->setInternal($name, $value);$this->loaded->set($name, '');}

此时我们明白,如果$immutable = true的话,如果之前环境变量有了该值,后面的配置文件无法进行更改环境变量的值,如果没有该值进行添加


http://www.ppmy.cn/devtools/127625.html

相关文章

2023年“网络建设与运维”广西省赛试题复盘

2023年“网络搭建与应用”省赛试题复盘 第一部分&#xff1a;网络搭建及安全部署项目 &#xff08;500分&#xff09; 一、竞赛内容分布 “网络搭建与应用”竞赛共分二个部分&#xff0c;其中&#xff1a; 第一部分&#xff1a;网络搭建及安全部署项目 第二部分&#xff1a;服…

SpringLDAP连接LDAPS证书报错解决办法(二)

一、前言 ​ 阅读此笔记之前需先了解之前的文章《SpringLDAP连接LDAPS证书报错解决办法》&#xff0c;之前文章中所阐述的不再一一重述。 二、现象描述 ​ 按照之前文章设置&#xff0c;在我所在的软件环境中有可能还会再出现SSL握手失败的异常&#xff0c;报错提示java.sec…

java导出带图形的word

先看效果图&#xff1a;方法都是一样的&#xff0c;所以数据只做了前两组 第一步需要准备模版&#xff1a; 新建一个word插入图表&#xff0c;选择想要的图表。 编辑图表&#xff1a;营业额表示数字&#xff0c;季度表示文字。其他的样式编辑可根据自己的需求更改&#xff0c;…

vscode 远程linux服务器 连接git

vscode 远程linux服务器 连接git 1. git 下载2. git 配置1&#xff09;github 设置2&#xff09;与github建立连接linux端&#xff1a;创建密钥github端&#xff1a;创建ssh key 3. 使用1&#xff09;初始化repository2&#xff09;commit 输入本次提交信息&#xff0c;提交到本…

Ubuntu18上,解决AndroidStudio中Device Explorer无法使用,Logcat无法使用的问题

具体原因时&#xff0c;Ubuntu中&#xff0c;默认adb版本使用过低&#xff0c;sudo apt-get adb版本过低 错误原因是因为之前用 sudo apt-get install adb 安装过 adb 通过 update-alternatives 使用 android studio 里面 Tools -> sdk manager -> SDK Tools -> And…

0.36秒即可完成一次高分辨率全球海洋预报!国防科技大学推出「羲和」大模型,性能超越主流数值预报系统,预报时长可达30天

在近日举行的第 20 届 CCF HPC China 2024 大会上&#xff0c;第六届海洋数值预报与高性能计算论坛圆满落幕。在该论坛中&#xff0c;国防科技大学气象海洋学院汪祥课题组助理研究员韩毅以「羲和&#xff1a;数据驱动的全球涡可分辨海洋环境预报大模型」为主题带来了深度分享。…

常用Python数据分析开源库:Numpy、Pandas、Matplotlib、Seaborn、Sklearn介绍

文章目录 1. 常用Python数据分析开源库介绍1.1 Numpy1.2 Pandas1.3 Matplotlib1.4 Seaborn1.5 Sklearn 1. 常用Python数据分析开源库介绍 1.1 Numpy Numpy(Numerical Python)是Python数据分析必不可少的第三方库&#xff0c;Numpy的出现一定程度上解决了Python运算性能不佳的…

Linux LCD 驱动实验

LCD 是很常用的一个外设&#xff0c;在裸机篇中我们讲解了如何编写 LCD 裸机驱动&#xff0c;在 Linux 下LCD 的使用更加广泛&#xff0c;再搭配 QT 这样的 GUI 库下可以制作出非常精美的 UI 界面。本章我们就来学习一下如何在 Linux 下驱动 LCD 屏幕。 Framebuffer 设备 先来…