一、运行原理概述
laravel 的入口文件 index.php
1、引入自动加载 autoload.php
2、创建应用实例,并同时完成了
基本绑定($this、容器类Container等等)、
基本服务提供者的注册(Event、log、routing)、
核心类别名的注册(比如db、auth、config、router等)
3、开始 Http 请求的处理
make 方法从容器中解析指定的值为实际的类,比如 $app->make(Illuminate\Contracts\Http\Kernel::class)
解析出 App\Http\Http.php handle
方法对 http 请求进行处理
实际上是 handle
中的 sendRequestThroughRouter
处理的 http
请求
首先,将 request
绑定到共享实例
然后执行 bootstarp
方法,运行给定的引导类数组 $bootstrappers
,这里很关键,包括了加载配置文件、环境变量、服务提供者(config/app.php
中的 providers
)、门面、异常处理、引导提供者
之后,进入管道模式,经过中间件的处理过滤后,再进行用户请求的分发
在请求分发时,首先,查找与给定请求匹配的路由,然后执行 runRoute
方法,实际处理请求的是 runRoute
方法中的 runRouteWithinStack
然后,经过 runRouteWithinStack
中的 run
方法,将请求分配到实际的控制器中,并得到响应结果
4、将处理结果返回
二、详细源码分析
1、注册自动加载器,实现文件的自动加载
require __dir__.'/../vendor/autoload.php';
2、创建应用容器实例 Application(该实例继承自容器类 Container), 并绑定核心(web、命令行、异常),以便在需要时解析它们
$app = require_once __DIR__.'/../bootstrap/app.php';
app.php 文件如下:
<?php
// 创建Laravel实例 【3】
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
// 绑定Web端kernel
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
// 绑定命令行kernel
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
// 绑定异常处理kernel
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
// 返回应用实例
return $app;
3、在创建应用实例(Application.php)的构造函数中,将基本绑定注册到容器中,并注册了所有的基本服务提供者,以及在容器中注册核心类别名
public function __construct($basePath = null)
{
// 将基本绑定注册到容器中【3.1】
$this->registerBaseBindings();
// 注册所有基本服务提供者【3.2】
$this->registerBaseServiceProviders();
// 在容器中注册核心类别名【3.3】
$this->registerCoreContainerAliases();
}
3.1、将基本绑定注册到容器中
static::setInstance($this);
$this->instance('app', $this);
$this->instance(Container::class, $this);
$this->singleton(Mix::class);
$this->instance(PackageManifest::class, new PackageManifest(
new Filesystem, $this->basePath(), $this->getCachedPackagesPath()
));
# 注:instance方法为将...注册为共享实例,singleton方法为将...注册为共享绑定
3.2、注册所有基本服务提供者 (事件、日志、路由)
protected function registerBaseServiceProviders()
{
$this->register(new EventServiceProvider($this));
$this->register(new LogServiceProvider($this));
$this->register(new RoutingServiceProvider($this));
}
3.3、在容器中注册核心类别名
4、上面完成了类的自动加载、服务提供者注册、核心类的绑定、以及基本注册的绑定
5、开始解析 http 请求
index.php
// 5.1
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
// 5.2
$response = $kernel->handle(