修改了配置文件config 发现逻辑代码中并没有生效。php
猜想缓存,因此执行下:laravel
php artisan config:cachebootstrap
缓存文件默认会存在bootstrap/cache 中,并不在storage中缓存
因此,,,,,呵呵app
参考:https://zhuanlan.zhihu.com/p/27570740编辑器
再来一篇源码解读系列,其实包含本篇 config:cache 源码解读在内,这三篇的源码解读都是跟线上环境部署 Laravel 项目有关,由于咱们一般会使用这三个 artisan 命令来提升项目的执行效率。因此,咱们进入正题:php artisan config:cache 源码解读ui
源码在哪
首先,咱们仍是可使用编辑器的搜索功能搜 ConfigCacheCommand,这样就能够直接打开 config:cache 命令的源代码了,位于 Illuminate\Foundation\Console\ConfigCacheCommand 中,关键的代码仍是位于 fire() 方法中:this
public function fire(){ $this->call('config:clear'); // other codes }
首先,在执行 php artisan config:cache 以前,咱们须要将以前缓存过的配置文件清除,就是经过 $this->call('config:clear'); 这一行代码来实现的。spa
那,config:clear 的源码在哪呢?code
这个命令的源码位于 Illuminate\Foundation\Console\ConfigClearCommand 中,你依然是能够在编辑器搜 ConfigClearCommand,而后定位到这里的 fire() 方法里面:
public function fire(){ $this->files->delete($this->laravel->getCachedConfigPath()); $this->info('Configuration cache cleared!'); }
你看,这里的代码就很是简单,主要就是删除原来缓存的配置文件,这个缓存的配置文件经过getCachedConfigPath() 获取到,这个 getCachedConfigPath() 在 Illuminate\Foundation\Application 中:
public function getCachedConfigPath(){ return $this->bootstrapPath().'/cache/config.php'; }
熟悉了吧,它也是放到 bootstrap/cache/ 目录下面的,命名为 config.php。
那么以上就删除完缓存的配置了,而后咱们再次回到 config:cache 中。既然旧的缓存已经删除,那么咱们就须要生成新的缓存文件了,因此再次聚焦 ConfigCacheCommand 的 fire() 方法:
public function fire(){ $config = $this->getFreshConfiguration(); $this->files->put( $this->laravel->getCachedConfigPath(), '<?php return '.var_export($config, true).';'.PHP_EOL ); }
首先 经过 getFreshConfiguration() 获取全部新的配置信息,这部分的代码逻辑就在 ConfigCacheCommand 中:
protected function getFreshConfiguration(){ $app = require $this->laravel->bootstrapPath().'/app.php'; $app->make(ConsoleKernelContract::class)->bootstrap(); return $app['config']->all(); }
这三行代码很简单,就是生成了一个 Laravel 的 Application 实例,而后经过 $app['config']->all() 获取全部的配置信息。
获取配置信息以后,就把新的配置信息写入缓存中,上面 ConfigCacheCommand fire() 方法的这一行实现:
$this->files->put( $this->laravel->getCachedConfigPath(), '<?php return '.var_export($config, true).';'.PHP_EOL );
getCachedConfigPath() 已经很熟悉啦,在讨论 cache:clear 时咱们就知道,其实就是获取到 bootstrap/cache/config.php 文件,而后写入配置的内容 var_export($config, true),因此最后缓存的配置文件大概的内容是这样的:
最后
有了缓存的配置文件,下次访问 Laravel 项目的时候就是直接读取缓存的配置了,而不用再次去计算和获取新的配置,这样来讲,速度依然会快那么一点点。