Laravel 源码学习笔记 5:请求通过中间件管道
上篇文章讲到请求通过kernel的handle方法解析,这篇主要讲handle里通过中间件的过程。
protected function sendRequestThroughRouter($request)
{
//绑定请求对象到容器
$this->app->instance('request', $request);
Facade::clearResolvedInstance('request');
//启动容器 ,分别启动里面的 env config 异常 注册facede 注册provider 引导provider
$this->bootstrap();
//请求通过管道中间件,分发匹配路由
return (new Pipeline($this->app))
->send($request)
->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
->then($this->dispatchToRouter());
}
这里是实例化管道对象,然后把请求放入管道
(关于管道模式,可以看下这个文章的介绍)
管道接口Illuminate\Contracts\Pipeline
管道实现类Illuminate\Pipeline\Pipeline
这是接口的方法:
Illuminate\Contracts\Pipeline
interface Pipeline
{
/**
* Set the traveler object being sent on the pipeline.
* 把要处理的任务放入管道
*
* @param mixed $traveler
* @return $this
*/
public function send($traveler);
/**
* Set the stops of the pipeline.
* 放入管道的几个中间件过滤
*
* @param dynamic|array $stops
* @return $this
*/
public function through($stops);
/**
* Set the method to call on the stops.
*
*
* @param string $method
* @return $this
*/
public function via($method);
/**
* Run the pipeline with a final destination callback.
* 处理
*
* @param \Closure $destination
* @return mixed
*/
public function then(Closure $destination);
}
这是几个基本的中间件
举个栗子
Illuminate\Foundation\Http\Middleware\ValidatePostSize 这个中间件
就是看post提交过来的数据的数量是否大于PHPini设置的最大数量。
管道中会有很多个中间件,请求经过一个又一个,类似多个回调返回一个回调的感觉。
through完成中间件过滤后,then分发给路由$this->dispatchToRouter()
- 找对应的路由实例
- 通过一个实例栈运行给定的路由
- 运行在 routes/web.php
- 配置的匹配到的控制器或匿名函数,返回响应结果。
有什么不对或有疑问的地方请大佬们指正:)
本作品采用《CC 协议》,转载必须注明作者和本文链接