laravel config 配置無效

修改了配置文件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 項目的時候就是直接讀取緩存的配置了,而不用再次去計算和獲取新的配置,這樣來講,速度依然會快那麼一點點。

相關文章
相關標籤/搜索