Laravel php artisan optimize 源码解读
原文:https://www.codecasts.com/blo...
在部署 Laravel 項(xiàng)目的時(shí)候,我們經(jīng)常會(huì)使用到一個(gè)提升性能的命令:
php artisan optimize本文來看看這個(gè)命令執(zhí)行背后的源碼:
首先我們可以使用編輯器搜 OptimizeCommand,應(yīng)該就可以找到該命令源碼的所在:
Illuminate\Foundation\Console\OptimizeCommand,我們關(guān)注其中的 fire() 方法:
fire() 方法,默認(rèn)情況下,會(huì)執(zhí)行$this->composer->dumpOptimized(),而這行代碼觸發(fā)的其實(shí)就是composer dump-autoload --optimize,源代碼可以在Illuminate\Support\Composer 的 dumpOptimized() 找到:
public function dumpOptimized(){$this->dumpAutoloads('--optimize');}最后,optimize 命令還執(zhí)行了call('clear-compiled'),其實(shí)就是觸發(fā)php artisan clear-compiled,而很巧的是,我們也是可以直接使用編輯器搜ClearCompiledCommand 來找到源碼,位于 Illuminate\Foundation\Console\ClearCompiledCommand 中,這里的 fire() 方法其實(shí)關(guān)鍵的一步就是刪除了一下 cache 下的文件,我們來看:
public function fire(){$servicesPath = $this->laravel->getCachedServicesPath();if (file_exists($servicesPath)) {@unlink($servicesPath);}$this->info('The compiled services file has been removed.');}通過確定 $servicesPath 的位置,再使用 @unlink($servicesPath); 刪除。
確定 $servicesPath 的代碼 $this->laravel->getCachedServicesPath() 位于 Illuminate\Foundation\Application 的 getCachedServicesPath 中:
public function getCachedServicesPath(){return $this->bootstrapPath().'/cache/services.php';}這樣一看,其實(shí)就是將 bootstrap/cache/services.php 文件刪除,而這個(gè) services.php 是 Laravel 會(huì)自動(dòng)生成的一個(gè)數(shù)組文件,這里指定了每個(gè) Providers 和 Facades 的位置和命名空間的全路徑等,在啟動(dòng) Laravel 項(xiàng)目的時(shí)候,可以直接讀取使用。
所以這個(gè)命令可以拆為兩步:
1.composer dump-autoload --optimize // composer 層面優(yōu)化加載速度 2.php artisan clear-compiled // 刪除 bootstrap/cache/services.php很清晰。
總結(jié)
以上是生活随笔為你收集整理的Laravel php artisan optimize 源码解读的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ajax初窥
- 下一篇: Thinkphp中import的几个用法