源碼解讀 Laravel PHP artisan config:cache


來源 https://laravel-china.org/articles/5101/source-code-reading-laravel-php-artisan-configcache

 

源碼在哪

首先,我們還是可以使用編輯器的搜索功能搜 ConfigCacheCommand,這樣就可以直接打開 config:cache 命令的源代碼了,位於 Illuminate\Foundation\Console\ConfigCacheCommand 中,關鍵的代碼還是位於 fire() 方法中:

public function fire(){ $this->call('config:clear'); // other codes }

首先,在執行 php artisan config:cache 之前,我們需要將之前緩存過的配置文件清除,就是通過 $this->call('config:clear'); 這一行代碼來實現的。

那,config:clear 的源碼在哪呢?

這個命令的源碼位於 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),所以最后緩存的配置文件大概的內容是這樣的:
config-cache.jpg

最后

有了緩存的配置文件,下次訪問 Laravel 項目的時候就是直接讀取緩存的配置了,而不用再次去計算和獲取新的配置,這樣來說,速度依然會快那么一點點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM