5. PHP 文件包含
配置缓存原理
接上一篇最后我们提出来一个问题:为何缓存配置信息即可提高运行效率呢?
这是因为 PHP 是脚本语言,每一次的用户请求,都会加载所有程序文件,随着我们的配置文件的增多,每一次程序启动所需加载的时间就会延长。
配置缓存的原理是将 config 文件夹下的所有 .php 文件合并到单一 bootstrap/cache/config.php 文件里,以此来达到加速的效果。
接下来我们来做一个测验,来统计下文件加载数量的信息。
首先我们新建中间件:
$ php artisan make:middleware PerformanceDebug打开此文件 app/Http/Middleware/PerformanceDebug.php ,写入以下代码:
app/Http/Middleware/PerformanceDebug.php
<?php
namespace App\Http\Middleware;
use Closure;
class PerformanceDebug
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        // 确保在开发环境下
        if (app()->isLocal()) {
            // 计算包含了多少文件
            $included_files_count = count(get_included_files());
            dd($included_files_count);
        }
        return $response;
    }
}保存后,我们还需要注册中间件,打开 Kernel.php,在 $middleware 全局中间件数组中注册我们的中间件:
app/Http/Kernel.php
<?php
.
.
.
class Kernel extends HttpKernel
{
    // 全局中间件
    protected $middleware = [
        .
        .
        .
        \App\Http\Middleware\PerformanceDebug::class,
    ];
    .
    .
    .
}修改后保存,并刷新浏览器,可以看到加载的文件数量:

这时候,我们命令行里:
$ php artisan config:clear清空配置缓存后,我们再刷新浏览器:

可以看出,我们在不使用配置缓存的情况下,每次要多加载 200 多个文件,因此影响了程序的响应时间。
为了方便后面课程的讲解,我们先把 中间件里 dd() 函数的调用注释掉:

Git 版本控制
接下来我们把代码整理好:
$ git add app/Http/Middleware/PerformanceDebug.php app/Http/Kernel.php
$ git commit -m "add log performance middleware"此时使用 git status 命令,可以看到 config 目录里刚刚创建的 200 个作为测试的文件。我们不再需要这些文件,请使用以下命令来删除这些文件。
注意:请再三检查你是否有未提交的文件,以下命令会删除所有更改和未跟踪的文件:
$ git clean -f -d 
           
         
                     
                     
         
             
             关于 LearnKu
                关于 LearnKu
               
                     
                     
                     粤公网安备 44030502004330号
 粤公网安备 44030502004330号