先来张图大致理解下laravel的生命周期。
下面对应相应的代码,解释上图。
//文件路径:laravel/public/index.php
/**
* laravel的启动时间
*/
define('LARAVEL_START', microtime(true));
/**
* 加载项目依赖。
* 现代PHP依赖于Composer包管理器,入口文件通过引入由Composer包管理器。
* 自动生成的类加载程序,可以轻松注册并加载所依赖的第三方组件库。
*/
require __DIR__.'/../vendor/autoload.php';
/**
* 创建laravel应用实例。
*/
$app = require_once __DIR__.'/../bootstrap/app.php';
// 接受请求并响应
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
// 结束请求,进行回调
$response->send();
// 终止程序
$kernel->terminate($request, $response);
//文件路径:laravel/boostrap/app.php
//第一部分:创建应用实例
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
//第二部分:完成内核绑定
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
return $app;
文件路径:laravel\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php
class Kernel implements KernelContract
{
protected $bootstrappers = [
\Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables::class, // 注册系统环境配置
\Illuminate\Foundation\Bootstrap\LoadConfiguration::class, // 注册系统配置
\Illuminate\Foundation\Bootstrap\HandleExceptions::class, // 注册异常注册
\Illuminate\Foundation\Bootstrap\RegisterFacades::class, // 注册门面模式
\Illuminate\Foundation\Bootstrap\RegisterProviders::class, // 注册服务提供者
\Illuminate\Foundation\Bootstrap\BootProviders::class, // 注册服务提供者boot
];
// 处理请求
public function handle($request)
{
try {
$request->enableHttpMethodParameterOverride();
$response = $this->sendRequestThroughRouter($request);
} catch (Exception $e) {
$this->reportException($e);
$response = $this->renderException($request, $e);
} catch (Throwable $e) {
$this->reportException($e = new FatalThrowableError($e));
$response = $this->renderException($request, $e);
}
$this->app['events']->dispatch(
new Events\RequestHandled($request, $response)
);
return $response;
}
protected function sendRequestThroughRouter($request)
{
//一、将$request实例注册到APP容器
$this->app->instance('request', $request);
//二、清除之前的$request实例缓存
Facade::clearResolvedInstance('request');
//三、启动引导程序
$this->bootstrap();
//四、发送请求
return (new Pipeline($this->app)) //创建管道
->send($request) //发送请求
->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware) //通过中间件
->then($this->dispatchToRouter()); //分发到路由
}
// 启动引导程序
public function bootstrap()
{
if (! $this->app->hasBeenBootstrapped()) {
$this->app->bootstrapWith($this->bootstrappers());
}
}
// 路由分发
protected function dispatchToRouter()
{
return function ($request) {
$this->app->instance('request', $request);
return $this->router->dispatch($request);
};
}
// 终止程序
public function terminate($request, $response)
{
$this->terminateMiddleware($request, $response);
$this->app->terminate();
}