Laravel的配置加载其实就是加载config目录下全部文件配置。如何过使用
php artisan config:cache
则会把加载的配置合并到一个配置文件中,下次请求就不会再去加载config目录。php
LoadEnvironmentVariables
.env环境配置加载。若是缓存配置是不会加载.env
的LoadConfiguration
判断是否缓存配置内核启动的时候。加载如下启动类json
\Illuminate\Foundation\Http\Kernel
类bootstrap
protected $bootstrappers = [ \Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class, // 加载 .env \Illuminate\Foundation\Bootstrap\LoadConfiguration::class, // 加载config配置 ... ];
本文重点讲解第二个config
配置加载。第一个请查看 深刻理解 Laravel 中.env 文件读取缓存
LoadConfiguration类中config配置加载的具体逻辑。app
其实就是判断缓存是否存在,存在则加载,不存在则递归遍历config
目录全部php
文件。若是运行php artisan config:cache
,则会把加载结果保存在bootstrap/cache
目录中;你可能还会看到services.php
文件,这是一个保存全部的服务提供者的文件,具体之后会讲。composer
public function bootstrap(Application $app) { $items = []; // 首先,咱们将看看是否有缓存配置文件。 若是是,咱们将从该文件加载配置项,所以它很是快。 // 不然,咱们须要遍历每一个配置文件并加载它们。 if (file_exists($cached = $app->getCachedConfigPath())) { // 加载缓存的配置文件 $items = require $cached; $loadedFromCache = true; } // 接下来,咱们将遍历配置目录中的全部配置文件,并将每一个配置文件加载到Repository中。 // 这将使开发人员可使用全部选项,以便在此应用程序的各个部分中使用。 $app->instance('config', $config = new Repository($items)); // 若是没有缓存配置才会去加载config目录 if (! isset($loadedFromCache)) { // 加载config目录全部PHP文件 $this->loadConfigurationFiles($app, $config); } //最后,咱们将根据加载的配置值设置应用程序的环境。 // 咱们将传递一个回调,该回调将用于在Web环境中获取环境,其中不存在“--env”开关。 $app->detectEnvironment(function () use ($config) { return $config->get('app.env', 'production'); }); // 设置时区 date_default_timezone_set($config->get('app.timezone', 'UTC')); mb_internal_encoding('UTF-8'); } /** * 从全部文件加载配置项。所以效率很低 * * @param \Illuminate\Contracts\Foundation\Application $app * @param \Illuminate\Contracts\Config\Repository $repository * @return void * @throws \Exception */ protected function loadConfigurationFiles(Application $app, RepositoryContract $repository) { // 遍历出全部PHP文件 $files = $this->getConfigurationFiles($app); if (! isset($files['app'])) { throw new Exception('Unable to load the "app" configuration file.'); } // 一个一个的加载 foreach ($files as $key => $path) { $repository->set($key, require $path); } }
php artisan config:cache
以后不会加载config配置,即使你修改了config目录中的配置文件也是不生效的,除非清除缓存php artisna config:clear
,或者从新缓存 php artisan config:cache
"autoload": { "classmap": [ "database/seeds", "database/factories" ], "psr-4": { "App\\": "app/" }, "files": [ # 这样那个会加载helpers.php文件了。该文件定义的是辅助函数 "bootstrap/helpers.php" ] },
config
中调用其余的 config('something.item')
是不会预期的加载的。由于不能保证配置something.item
已经加载到了