laravel 框架执行流程与原理简单分析

2020-02-02 08:03:39丽君

本文实例讲述了laravel 框架执行流程与原理。,具体如下:

1.index.php

$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(IlluminateContractsHttpKernel::class);
$response = $kernel->handle(
  $request = IlluminateHttpRequest::capture()
);

2.进入app.php

$app = new IlluminateFoundationApplication(
  $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
$app->singleton(
  IlluminateContractsHttpKernel::class,
  AppHttpKernel::class
);

Application 类绑定基本类到容器

Kernel 类执行路由分发加载控制器等操作

3.进入 Kernel.php

// 全局路由中间件,每次执行都会执行
protected $middleware = [];
// 中间件路由分组,
protected $middlewareGroups = [];
// 中间件别名,可以单独使用也可以分配给组
protected $routeMiddleware = [];
// 中间件排序
protected $middlewarePriority = [];

kernel 类继承 IlluminateFoundationHttpKernel 类

4.进入 IlluminateFoundationHttpKernel 类

//http方法参数覆盖,也就是 X-HTTP-METHOD-OVERRIDE 中有参数,就按照这个里面的走,如果没有,那就是post
$request->enableHttpMethodParameterOverride();
// 通过中间件/路由器发送给定的请求。
$response = $this->sendRequestThroughRouter($request);
// 触发事件并呼叫听众 韩注:触发观察者
$this->app['events']->dispatch(
new EventsRequestHandled($request, $response)
);
return $response;

进入 sendRequestThroughRouter 方法

// 注册请求类到容器中
 $this->app->instance('request', $request);
// 从facade根实例 中删除共享实例
Facade::clearResolvedInstance('request');
// 启动引导类  protected $bootstrappers = []; 引导类都在这个数组中
$this->bootstrap();
// 通过管道模式执行最终结果,切面编程,aop 
 return (new Pipeline($this->app))
          // 设置通过管道发送的对象
          ->send($request)
          // 设置管道阵列。
          // shouldSkipMiddleware  判断是否应该跳过中间件,$this->make('middleware.disable') 设置为true
          // $this->bound('middleware.disable') 设置为true 应该可以跳过 所有中间件,不知道这么做的好处是什么?
          ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
          // 使用最终目标回调运行管道,最终需要运行的结果
          ->then($this->dispatchToRouter());

进入 dispatchToRouter 路由分发 ,最终由路由类中 dispatch 执行路由,并实现注入

$this->router->dispatch($request);

利用反射原理实现依赖注入 IlluminateContainerContainer 类中

public function make($abstract, array $parameters = []){
  return $this->resolve($abstract, $parameters);
}
public function build($concrete)
// build 中
$reflector = new ReflectionClass($concrete);

								 
			 
相关文章 大家在看