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);
}

这是几个基本的中间件
image
举个栗子
Illuminate\Foundation\Http\Middleware\ValidatePostSize 这个中间件
就是看post提交过来的数据的数量是否大于PHPini设置的最大数量。
image
管道中会有很多个中间件,请求经过一个又一个,类似多个回调返回一个回调的感觉。
through完成中间件过滤后,then分发给路由$this->dispatchToRouter()

  1. 找对应的路由实例
  2. 通过一个实例栈运行给定的路由
  3. 运行在 routes/web.php
  4. 配置的匹配到的控制器或匿名函数,返回响应结果。

    有什么不对或有疑问的地方请大佬们指正:)

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!