Laravel 5.x 启动过程分析


1、初始化Application

1.1 注册基本绑定

  • app -> Application实例(IlluminateFoundationApplication)
  • IlluminateContainerContainer -> Application实例(IlluminateFoundationApplication)

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

EventServieProvider —— 事件服务提供者

$this->app->singleton('events', function ($app) {
    return (new Dispatcher($app))->setQueueResolver(function () use ($app) {
        return $app->make('IlluminateContractsQueueFactory');
    });
});

RoutingServiceProvider —— 路由服务提供者

public function register()
{
    $this->registerRouter();
    $this->registerUrlGenerator();
    $this->registerRedirector();
    $this->registerPsrRequest();
    $this->registerPsrResponse();
    $this->registerResponseFactory();
}

更多详情查看源码:IlluminateRoutingRoutingServiceProvider.php

1.3 注册核心服务容器别名

更多详情查看源码:IlluminateFoundationApplication.php第1026行registerCoreContainerAliases方法。

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

if ($basePath) {
    $this->setBasePath($basePath);
}

更多详情查看源码:IlluminateFoundationApplication.php第262行setBasePath方法。

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

  • IlluminateContractsHttpKernel -> AppHttpKernel
  • IlluminateContractsConsoleKernel -> AppConsoleKernel
  • IlluminateContractsDebugExceptionHandler -> AppExceptionsHandler

3、处理请求和响应

3.1 web请求

解析IlluminateContractsHttpKernel,实例化AppHttpKernel

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

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

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

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

$response->send();

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

$kernel->terminate($request, $response);
原文地址:https://www.cnblogs.com/mouseleo/p/8617330.html