Laravel 源码解读:PHP artisan down 
                                                    
                        
                    
                    
  
                    
                    Laravel 的 php artisan down 命令通常是在我们维护的时候使用的,因为在执行这条命令的时候,我们的 laravel 应用就进入了维护模式,会出现一个类似于下面这个 Be Ringht Back 页面
源码在哪
还是一样,我们首先找到 artisan down 命令的源码所在,它位于 Illuminate\Foundation\Console\DownCommand 中
Tips:依然是可以直接使用编辑器搜索
DownCommand。
解读
主体方法还是 fire():
public function fire()
    {
        file_put_contents(
            $this->laravel->storagePath().'/framework/down',
            json_encode($this->getDownFilePayload(), JSON_PRETTY_PRINT)
        );
        $this->comment('Application is now in maintenance mode.');
    }
这里的代码其实非常简单,就是使用 file_put_contents() 将 json_encode($this->getDownFilePayload() 内容写入storage/framework/down 文件中,这个文件很重要!。storagePath() 就是位于 Illuminate\Foundation\Application 中的:
 public function storagePath()
    {
        return $this->storagePath ?: $this->basePath.DIRECTORY_SEPARATOR.'storage';
    }
也就是项目目录的 storage/ 文件路径。
写入的内容是什么?
文件内容是由 $this->getDownFilePayload() 生成,其实很简单的,就是在 DownCommand 中:
 protected function getDownFilePayload()
    {
        return [
            'time' => Carbon::now()->getTimestamp(),
            'message' => $this->option('message'),
            'retry' => $this->getRetryTime(),
        ];
    }
这里只返回一个数组,记录三个关键的信息:time , message, retry;这样看来其实我们可以自定义 Be Right Back 的字样的吧,也可以定义提示的时间,我们可以这样验证:
然后这样使用:

怎么判断是否是维护模式
超级简单,就在 Laravel 的核心类 Illuminate\Foundation\Application 中,启动之前先检查是否是维护模式 isDownForMaintenance():
 public function isDownForMaintenance()
    {
        return file_exists($this->storagePath().'/framework/down');
    }
你看,简单吧!它就是直接检测 storage/framework/down 是否存在!Neat!
最后
总结就是,执行 php artisan down 命令的时候,主要是生成 storage/framework/down 文件,包含了 time message 和 retry 三个关键信息,然后在 Laravel 启动的时候检测 storage/framework/down 文件是否存在就可以了。如果存在该文件,那就认为项目处于维护状态。
广告时间
坚持每天更新的公众号 codecasts,最近也在送书!有兴趣的可以关注一下
本作品采用《CC 协议》,转载必须注明作者和本文链接
          
                    
                    
            
 。那么如何能给客户端返回正确的 
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: