在部署 Laravel 项目的时候,我们经常会使用到一个提升性能的命令: php artisan optimize 本文来看看这个命令执行背后的源码: 首先我们可以使用编辑器搜 OptimizeCommand,应该就可以找到该命令源码的所在: Illuminate\Foundation\Console\OptimizeCommand, 我们关注其中的 fire() 方法: ~~~ public function fire() { $this->info('Generating optimizedclass loader'); if ($this->option('psr')) { $this->composer->dumpAutoloads(); } else { $this->composer->dumpOptimized(); } $this->call('clear-compiled'); } ~~~ fire() 方法,默认情况下,会执行 `$this->composer->dumpOptimized()` 而这行代码触发 的其实就是 `composer dump-autoload --optimize` 源代码可以在 Illuminate\Support\Composer 的 dumpOptimized() 找到: ~~~ public function dumpOptimized() { $this->dumpAutoloads('--optimize'); } ~~~ 最后,optimize 命令还执行了 `call('clear-compiled')` 其实就是触发 `php artisanclear-compiled` 而很巧的是,我们也是可以直接使用编辑器搜ClearCompiledCommand 来 找到源码,位于 `Illuminate\Foundation\Console\ClearCompiledCommand ` 中,这里的 fire() 方法其实关键的一步就是删除了一下 cache 下的文件,我们来看: ~~~ public function fire() { $servicesPath = $this->laravel->getCachedServicesPath(); if (file_exists($servicesPath)) { @unlink($servicesPath); } $this->info('The compiled services file has beenremoved.'); } ~~~ 通过确定 $servicesPath 的位置,再使用 @unlink($servicesPath); 删除。 确定 $servicesPath 的代码 `$this->laravel->getCachedServicesPath() ` 位于 Illuminate\Foundation\Application 的 getCachedServicesPath 中: ~~~ public function getCachedServicesPath() { return $this->bootstrapPath().'/cache/services.php'; } ~~~ 这样一看,其实就是将 bootstrap/cache/services.php 文件删除,而这 个 services.php 是 Laravel 会自动生成的一个数组文件,这里指定了每个 Providers和 Facades 的位置和命名空间的全路径等,在启动 Laravel 项目的时候,可以直接读取使 用。 所以这个命令可以拆为两步: 1.`composer dump-autoload --optimize // composer 层面优化加载速度`2.`php artisan clear-compiled // 删除 bootstrap/cache/services.php` 很清晰。