Laravel 5.x 启动过程分析


1、初始化Application

1.1 注册基本绑定

  • app -> Application实例(Illuminate\Foundation\Application)
  • Illuminate\Container\Container -> Application实例(Illuminate\Foundation\Application)

1.2 注册基本服务提供者并启动

EventServieProvider —— 事件服务提供者

  1. $this->app->singleton('events', function ($app) {
  2. return (new Dispatcher($app))->setQueueResolver(function () use ($app) {
  3. return $app->make('Illuminate\Contracts\Queue\Factory');
  4. });
  5. });

RoutingServiceProvider —— 路由服务提供者

  1. public function register()
  2. {
  3. $this->registerRouter();
  4. $this->registerUrlGenerator();
  5. $this->registerRedirector();
  6. $this->registerPsrRequest();
  7. $this->registerPsrResponse();
  8. $this->registerResponseFactory();
  9. }

更多详情查看源码:Illuminate\Routing\RoutingServiceProvider.php

1.3 注册核心服务容器别名

更多详情查看源码:Illuminate\Foundation\Application.php第1026行registerCoreContainerAliases方法。

1.4 设置根路径(如果传入的话)

  1. if ($basePath) {
  2. $this->setBasePath($basePath);
  3. }

更多详情查看源码:Illuminate\Foundation\Application.php第262行setBasePath方法。

2、注册共享的Kernel和异常处理器

  • Illuminate\Contracts\Http\Kernel -> App\Http\Kernel
  • Illuminate\Contracts\Console\Kernel -> App\Console\Kernel
  • Illuminate\Contracts\Debug\ExceptionHandler -> App\Exceptions\Handler

3、处理请求和响应

3.1 web请求

解析Illuminate\Contracts\Http\Kernel,实例化App\Http\Kernel

a.构造函数:设置$app/$router,初始化$router中middleware数值

b.handle处理请求 —— 经过路由发送请求:

  • $request是经过Symfony封装的请求对象
  • 注册request实例到容器 ($app[‘request’]->Illuminate\Http\Request)
  • 清空之前容器中的request实例
  • 调用bootstrap方法,启动一系列启动类的bootstrap方法:
    1. Illuminate\Foundation\Bootstrap\DetectEnvironment 环境配置($app[‘env’])
    2. Illuminate\Foundation\Bootstrap\LoadConfiguration  基本配置($app[‘config’])
    3. Illuminate\Foundation\Bootstrap\ConfigureLogging   日志文件($app[‘log’])
    4. Illuminate\Foundation\Bootstrap\HandleExceptions   错误&异常处理
    5. Illuminate\Foundation\Bootstrap\RegisterFacades    清除已解析的Facade并重新启动,注册config文件中alias定义的所有Facade类到容器
    6. Illuminate\Foundation\Bootstrap\RegisterProviders  注册config中providers定义的所有Providers类到容器
    7. Illuminate\Foundation\Bootstrap\BootProviders      调用所有已注册Providers的boot方法
  • 通过Pipeline发送请求,经过中间件,再由路由转发,最终返回响应
    1. new Pipeline($this->app))
    2. ->send($request)
    3.         ->through($this->middleware)
    4.         ->then($this->dispatchToRouter()

c.将响应信息发送到浏览器:

  1. $response->send();

d.处理继承自TerminableMiddleware接口的中间件(Session)并结束应用生命周期:

  1. $kernel->terminate($request, $response);