Laravel php artisan optimize 源码解读

原文:https://www.codecasts.com/blo...php

在部署 Laravel 项目的时候,咱们常常会使用到一个提高性能的命令:laravel

php artisan optimize

本文来看看这个命令执行背后的源码:bootstrap

首先咱们能够使用编辑器搜 OptimizeCommand,应该就能够找到该命令源码的所在:
Illuminate\Foundation\Console\OptimizeCommand,咱们关注其中的 fire() 方法:数组

public function fire()
    {
        $this->info('Generating optimized class loader');

        if ($this->option('psr')) {
            $this->composer->dumpAutoloads();
        } else {
            $this->composer->dumpOptimized();
        }

        $this->call('clear-compiled');
    }

fire() 方法,默认状况下,会执行$this->composer->dumpOptimized(),而这行代码触发的其实就是composer dump-autoload --optimize,源代码能够在Illuminate\Support\ComposerdumpOptimized() 找到:composer

public function dumpOptimized()
    {
        $this->dumpAutoloads('--optimize');
    }

最后,optimize 命令还执行了call('clear-compiled'),其实就是触发php artisan clear-compiled,而很巧的是,咱们也是能够直接使用编辑器搜ClearCompiledCommand 来找到源码,位于 Illuminate\Foundation\Console\ClearCompiledCommand 中,这里的 fire() 方法其实关键的一步就是删除了一下 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); 删除。ide

肯定 $servicesPath 的代码 $this->laravel->getCachedServicesPath() 位于 Illuminate\Foundation\ApplicationgetCachedServicesPath 中:post

public function getCachedServicesPath()
    {
        return $this->bootstrapPath().'/cache/services.php';
    }

这样一看,其实就是将 bootstrap/cache/services.php 文件删除,而这个 services.php 是 Laravel 会自动生成的一个数组文件,这里指定了每一个 Providers 和 Facades 的位置和命名空间的全路径等,在启动 Laravel 项目的时候,能够直接读取使用。性能

因此这个命令能够拆为两步:优化

1.composer dump-autoload --optimize // composer 层面优化加载速度
2.php artisan clear-compiled // 删除 bootstrap/cache/services.php

很清晰。

相关文章
相关标签/搜索