Laravel学习笔记之Middleware源码解析

6

说明:本文主要学习Laravel的Middleware的源码设计思想,并将学习心得分享出来,希望对别人有所帮助。Laravel学习笔记之Decorator Pattern已经聊过Laravel使用了Decorator Pattern来设计Middleware,看Laravel源码发现其巧妙用了Closure和PHP的一些数组函数来设计Middleware。

开发环境:Laravel5.3 + PHP7 + OS X 10.11

PHP内置函数array_reverse、array_reduce、call_user_func和call_user_func_array

看Laravel源码之前,先看下这几个PHP内置函数的使用。首先array_reverse()函数比较简单,倒置数组,看测试代码:

$pipes = [
    'Pipe1',
    'Pipe2',
    'Pipe3',
    'Pipe4',
    'Pipe5',
    'Pipe6',
];

$pipes = array_reverse($pipes);

var_dump($pipes);

// output
array(6) {
  [0] =>
  string(5) "Pipe6"
  [1] =>
  string(5) "Pipe5"
  [2] =>
  string(5) "Pipe4"
  [3] =>
  string(5) "Pipe3"
  [4] =>
  string(5) "Pipe2"
  [5] =>
  string(5) "Pipe1"
}

array_reduce内置函数主要是用回调函数去迭代数组中每一个值,并且每一次回调得到的结果值作为下一次回调的初始值,最后返回最终迭代的值:

/**
 * @link http://php.net/manual/zh/function.array-reduce.php
 * @param int $v
 * @param int $w
 *
 * @return int
 */
function rsum($v, $w)
{
    $v += $w;
    return $v;
}

$a = [1, 2, 3, 4, 5];
// 10为初始值
$b = array_reduce($a, "rsum", 10);
// 最后输出 (((((10 + 1) + 2) + 3) + 4) + 5) = 25
echo $b . PHP_EOL; 

call_user_func()是执行回调函数,并可输入参数作为回调函数的参数,看测试代码:

class TestCallUserFunc
{
    public function index($request)
    {
        echo $request . PHP_EOL;
    }
}   

/**
 * @param $test
 */
function testCallUserFunc($test)
{
    echo $test . PHP_EOL;
}

// [$class, $method]
call_user_func(['TestCallUserFunc', 'index'], 'pipes'); // 输出'pipes'

// Closure
call_user_func(function ($passable) {
    echo $passable . PHP_EOL;
}, 'pipes'); // 输出'pipes'

// function
call_user_func('testCallUserFunc' , 'pipes'); // 输出'pipes'

call_user_func_array与call_user_func基本一样,只不过传入的参数是数组:

class TestCallUserFuncArray
{
    public function index($request)
    {
        echo $request . PHP_EOL;
    }
}

/**
 * @param $test
 */
function testCallUserFuncArray($test)
{
    echo $test . PHP_EOL;
}

// [$class, $method]
call_user_func_array(['TestCallUserFuncArray', 'index'], ['pipes']); // 输出'pipes'

// Closure
call_user_func_array(function ($passable) {
    echo $passable . PHP_EOL;
}, ['pipes']); // 输出'pipes'

// function
call_user_func_array('testCallUserFuncArray' , ['pipes']); // 输出'pipes'

Middleware源码解析

了解了几个PHP内置函数后再去看下Middleware源码就比较简单了。Laravel学习笔记之IoC Container实例化源码解析已经聊过Application的实例化,得到index.php中的$app变量,即\Illuminate\Foundation\Application的实例化对象。然后继续看下index.php的源码:

/**
 * @var \App\Http\Kernel $kernel
 */
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

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

首先从容器中解析出Kernel对象,对于\App\Http\Kernel对象的依赖:\Illuminate\Foundation\Application和\Illuminate\Routing\Router,容器会自动解析。看下Kernel的构造函数:

    /**
     * Create a new HTTP kernel instance.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @param  \Illuminate\Routing\Router  $router
     */
    public function __construct(Application $app, Router $router)
    {
        $this->app    = $app;
        $this->router = $router;

        foreach ($this->middlewareGroups as $key => $middleware) {
            $router->middlewareGroup($key, $middleware);
        }

        foreach ($this->routeMiddleware as $key => $middleware) {
            $router->middleware($key, $middleware);
        }
    }
    
    // \Illuminate\Routing\Router内的方法
    public function middlewareGroup($name, array $middleware)
    {
        $this->middlewareGroups[$name] = $middleware;

        return $this;
    }
    
    public function middleware($name, $class)
    {
        $this->middleware[$name] = $class;

        return $this;
    }

构造函数初始化了几个中间件数组,$middleware[ ], $middlewareGroups[ ]和$routeMiddleware[ ],Laravel5.0的时候记得中间件数组还没有分的这么细。然后就是Request的实例化:


$request = Illuminate\Http\Request::capture()

这个过程以后再聊吧,不管咋样,得到了Illuminate\Http\Request对象,然后传入Kernel中:

    /**
     * Handle an incoming HTTP request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function handle($request)
    {
        try {
            $request->enableHttpMethodParameterOverride();

            $response = $this->sendRequestThroughRouter($request);
        } catch (Exception $e) {
            $this->reportException($e);

            $response = $this->renderException($request, $e);
        } catch (Throwable $e) {
            $this->reportException($e = new FatalThrowableError($e));

            $response = $this->renderException($request, $e);
        }

        $this->app['events']->fire('kernel.handled', [$request, $response]);

        return $response;
    }

主要是sendRequestThroughRouter($request)函数执行了转换操作:把\Illuminate\Http\Request对象转换成了\Illuminate\Http\Response,然后通过Kernel的send()方法发送给客户端。同时,顺便触发了kernel.handled内核已处理请求事件。OK,重点关注下sendRequestThroughRouter($request)方法:

    /**
     * Send the given request through the middleware / router.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    protected function sendRequestThroughRouter($request)
    {
        $this->app->instance('request', $request);

        Facade::clearResolvedInstance('request');

        /* 依次执行$bootstrappers中每一个bootstrapper的bootstrap()函数,做了几件准备事情:
        1. 环境检测
        2. 配置加载
        3. 日志配置
        4. 异常处理
        5. 注册Facades
        6. 注册Providers
        7. 启动服务
         protected $bootstrappers = [
            'Illuminate\Foundation\Bootstrap\DetectEnvironment',
            'Illuminate\Foundation\Bootstrap\LoadConfiguration',
            'Illuminate\Foundation\Bootstrap\ConfigureLogging',
            'Illuminate\Foundation\Bootstrap\HandleExceptions',
            'Illuminate\Foundation\Bootstrap\RegisterFacades',
            'Illuminate\Foundation\Bootstrap\RegisterProviders',
            'Illuminate\Foundation\Bootstrap\BootProviders',
        ];*/
        $this->bootstrap();

        return (new Pipeline($this->app))
                    ->send($request)
                    ->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
                    ->then($this->dispatchToRouter());
    }

$this->bootstrap()主要是做了程序初始化工作,以后再聊具体细节。然后是Pipeline来传输Request,Laravel中把Pipeline管道单独拿出来作为一个service(可看Illuminate/Pipeline文件夹),说明Pipeline做的事情还是很重要的:主要就是作为Request的传输管道,依次通过$middlewares[ ], 或middlewareGroups[ ], 或$routeMiddleware[ ]这些中间件的前置操作,和控制器的某个action或者直接闭包处理得到Response,然后又带着Reponse依次通过$middlewares[ ], 或middlewareGroups[ ], 或$routeMiddleware[ ]这些中间件的后置操作得到准备就绪的Response,然后通过send()发送给客户端。
这个过程有点像汽车工厂的生产一样,Pipeline是传送带,起初Request可能就是个汽车空壳子,经过传送带旁边的一个个机械手middleware@before的过滤和操作(如检查零件刚度是不是合格,壳子尺寸是不是符合要求,给壳子喷个漆或抹个油啥的),然后进入中央控制区加个发动机(Controller@action ,或Closure),然后又继续经过检查和附加操作middleware@after(如添加个挡风镜啥的),然后通过门外等着的火车直接运送到消费者手里send()。在每一步装配过程中,都需要Service来支持,Service是通过Container来解析{make()}提供的,并且Service是通过ServiceProvider注册绑定{bind(),singleton(),instance()}到Container中的。

看下Pipeline的send()和through()源码:

    public function send($passable)
    {
        $this->passable = $passable;

        return $this;
    }
    
    public function through($pipes)
    {
        $this->pipes = is_array($pipes) ? $pipes : func_get_args();

        return $this;
    }

send()传送的对象是Request,through()所要通过的对象是$middleware[ ],OK,再看下dispatchToRouter()的源码直接返回一个Closure:

    protected function dispatchToRouter()
    {
        return function ($request) {
            $this->app->instance('request', $request);

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

然后重点看下then()函数源码:

    public function then(Closure $destination)
    {
        $firstSlice = $this->getInitialSlice($destination);

        $pipes = array_reverse($this->pipes);

        // $this->passable = Request对象
        return call_user_func(
            array_reduce($pipes, $this->getSlice(), $firstSlice), $this->passable
        );
    }
    
    protected function getInitialSlice(Closure $destination)
    {
        return function ($passable) use ($destination) {
            return call_user_func($destination, $passable);
        };
    }

这里假设$middlewares为(尽管源码中$middlewares只有一个CheckForMaintenanceMode::class):

$middlewares = [
    CheckForMaintenanceMode::class,
    AddQueuedCookiesToResponse::class,
    StartSession::class,
    ShareErrorsFromSession::class,
    VerifyCsrfToken::class,
];

先获得第一个slice(这里作者是比作'洋葱',一层层的穿过,从一侧穿过到另一侧,比喻倒也形象)并作为array_reduce()的初始值,就像上文中array_reduce()测试例子中的10这个初始值,这个初始值现在是个闭包:

$destination = function ($request) {
    $this->app->instance('request', $request);
    return $this->router->dispatch($request);
};

$firstSlice = function ($passable) use ($destination) {
    return call_user_func($destination, $passable);
};

OK,然后要对$middlewares[ ]进行翻转,为啥要翻转呢?
看过这篇Laravel学习笔记之Decorator Pattern文章就会发现,在Client类利用Decorator Pattern进行依次装饰的时候,是按照$middlewares[ ]数组中值倒着new的:

    public function wrapDecorator(IMiddleware $decorator)
    {
        $decorator = new VerifyCsrfToken($decorator);
        $decorator = new ShareErrorsFromSession($decorator);
        $decorator = new StartSession($decorator);
        $decorator = new AddQueuedCookiesToResponse($decorator);
        $response  = new CheckForMaintenanceMode($decorator);

        return $response;
    }

这样才能得到一个符合$middlewares[ ]顺序的$response对象:

$response = new CheckForMaintenanceMode(
                new AddQueuedCookiesToResponse(
                    new StartSession(
                        new ShareErrorsFromSession(
                            new VerifyCsrfToken(
                                new Request()
                        )
                    )
                )
            )
        );

看下array_reduce()中的迭代回调函数getSlice(){这个迭代回调函数比作剥洋葱时获取每一层洋葱slice,初始值是$firstSlice}:

    protected function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                if ($pipe instanceof Closure) {
                    return call_user_func($pipe, $passable, $stack);
                } elseif (! is_object($pipe)) {
                    list($name, $parameters) = $this->parsePipeString($pipe);
                    $pipe = $this->container->make($name);
                    $parameters = array_merge([$passable, $stack], $parameters);
                } else{
                    $parameters = [$passable, $stack];
                }

                return call_user_func_array([$pipe, $this->method], $parameters);
            };
        };
    }

返回的是个闭包,仔细看下第二层闭包里的逻辑,这里$middlewares[ ]传入的是每一个中间件的名字,然后通过容器解析出每一个中间件对象:

$pipe = $this->container->make($name);

并最后用call_user_func_array([$class, $method], array $parameters)来调用这个$class里的$method方法,参数是$parameters。

Demo

接下来写个demo看下整个流程。
先简化下getSlice()函数,这里就默认$pipe传入的是类名称(整个demo中所有class都在同一个文件内):

// PipelineTest.php

// Get the slice in every step.
function getSlice()
{
    return function ($stack, $pipe) {
        return function ($passable) use ($stack, $pipe) {
            /**
             * @var Middleware $pipe
             */
            return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
        };
    };
}

再把$middlewares[ ]中五个中间件类写上,对于前置操作和后置操作做个简化,直接echo字符串:

// PipelineTest.php

<?php

interface Middleware
{
    public static function handle($request, Closure $closure);
}

class CheckForMaintenanceMode implements Middleware
{
    public static function handle($request, Closure $next)
    {
        echo $request . ': Check if the application is in the maintenance status.' . PHP_EOL;
        $next($request);
    }
}

class AddQueuedCookiesToResponse implements Middleware
{
    public static function handle($request, Closure $next)
    {
        $next($request);
        echo $request . ': Add queued cookies to the response.' . PHP_EOL;
    }
}

class StartSession implements Middleware
{
    public static function handle($request, Closure $next)
    {
        echo $request . ': Start session of this request.' . PHP_EOL;
        $next($request);
        echo $request . ': Close session of this response.' . PHP_EOL;
    }
}

class ShareErrorsFromSession implements Middleware
{
    public static function handle($request, Closure $next)
    {
        $next($request);
        echo $request . ': Share the errors variable from response to the views.' . PHP_EOL;
    }
}

class VerifyCsrfToken implements Middleware
{
    public static function handle($request, Closure $next)
    {
        echo $request . ': Verify csrf token when post request.' . PHP_EOL;
        $next($request);
    }
}

给上完整的一个Pipeline类,这里的Pipeline对Laravel中的Pipeline做了稍微简化,只选了几个重要的函数:

// PipelineTest.php

class Pipeline 
{
    /**
     * @var array
     */
    protected $middlewares = [];

    /**
     * @var int
     */
    protected $request;

    // Get the initial slice
    function getInitialSlice(Closure $destination)
    {
        return function ($passable) use ($destination) {
            return call_user_func($destination, $passable);
        };
    }
    
    // Get the slice in every step.
    function getSlice()
    {
        return function ($stack, $pipe) {
            return function ($passable) use ($stack, $pipe) {
                /**
                 * @var Middleware $pipe
                 */
                return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
            };
        };
    }
    
    // When process the Closure, send it as parameters. Here, input an int number.
    function send(int $request)
    {
        $this->request = $request;
        return $this;
    }

    // Get the middlewares array.
    function through(array $middlewares)
    {
        $this->middlewares = $middlewares;
        return $this;
    }
    
    // Run the Filters.
    function then(Closure $destination)
    {
        $firstSlice = $this->getInitialSlice($destination);
    
        $pipes = array_reverse($this->middlewares);
        
        $run = array_reduce($pipes, $this->getSlice(), $firstSlice);
    
        return call_user_func($run, $this->request);
    }
}

OK,现在开始传入Request,这里简化为一个整数而不是Request对象了:

// PipelineTest.php

/**
 * @return \Closure
 */
function dispatchToRouter()
{
    return function ($request) {
        echo $request . ': Send Request to the Kernel, and Return Response.' . PHP_EOL;
    };
}

$request = 10;

$middlewares = [
    CheckForMaintenanceMode::class,
    AddQueuedCookiesToResponse::class,
    StartSession::class,
    ShareErrorsFromSession::class,
    VerifyCsrfToken::class,
];

(new Pipeline())->send($request)->through($middlewares)->then(dispatchToRouter());

执行php PipelineTest.php得到Response:

10: Check if the application is in the maintenance status.
10: Start session of this request.
10: Verify csrf token when post request.
10: Send Request to the Kernel, and Return Response.
10: Share the errors variable from response to the views.
10: Close session of this response.
10: Add queued cookies to the response.

一步一步分析下执行过程:

1.首先获取$firstSlice

$destination = function ($request) {
    echo $request . ': Send Request to the Kernel, and Return Response.' . PHP_EOL;
};
$firstSlice = function ($passable) use ($destination) {
    return call_user_func($destination, $passable);
};

这时经过初始化后:

$this->request = 10;
$pipes = [
    VerifyCsrfToken::class,
    ShareErrorsFromSession::class,
    StartSession::class,
    AddQueuedCookiesToResponse::class,
    CheckForMaintenanceMode::class,
];

2.执行第一次getSlice()后的结果作为新的$stack,其值为:

$stack   = $firstSlice;
$pipe    = VerifyCsrfToken::class;
$stack_1 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

3.执行第二次getSlice()后的结果作为新的$stack,其值为:

$stack   = $stack_1;
$pipe    = ShareErrorsFromSession::class;
$stack_2 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

4.执行第三次getSlice()后的结果作为新的$stack,其值为:

$stack   = $stack_2;
$pipe    = StartSession::class;
$stack_3 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

5.执行第四次getSlice()后的结果作为新的$stack,其值为:

$stack   = $stack_3;
$pipe    = AddQueuedCookiesToResponse::class;
$stack_4 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

6.执行第五次getSlice()后的结果作为新的$stack,其值为:

$stack   = $stack_4;
$pipe    = CheckForMaintenanceMode::class;
$stack_5 = function ($passable) use ($stack, $pipe) {
        /**
        * @var Middleware $pipe
        */            
    return call_user_func_array([$pipe, 'handle'], [$passable, $stack]);
};

这时,$stack_5也就是then()里的$run,然后执行call_user_func($run, 10),看执行过程:

1.$stack_5(10) = CheckForMaintenanceMode::handle(10, $stack_4)

echo '10: Check if the application is in the maintenance status.' . PHP_EOL;
stack_4(10);

2.$stack_4(10) = AddQueuedCookiesToResponse::handle(10, $stack_3)

$stack_3(10);
echo '10: Add queued cookies to the response.' . PHP_EOL;

3.$stack_3(10) = StartSession::handle(10, $stack_2)

echo '10: Start session of this request.' . PHP_EOL;
$stack_2(10);
echo '10: Close session of this response.' . PHP_EOL;

4.$stack_2(10) = ShareErrorsFromSession::handle(10, $stack_1)

$stack_1(10);
echo '10: Share the errors variable from response to the views.' . PHP_EOL;

5.$stack_1(10) = VerifyCsrfToken::handle(10, $firstSlice)

echo '10: Verify csrf token when post request.' . PHP_EOL;
$firstSlice(10);

6.$firstSlice(10) =

$firstSlice(10) = call_user_func($destination, 10) = echo '10: Send Request to the Kernel, and Return Response.' . PHP_EOL;

OK,再把上面执行顺序整理一下:

1. echo '10: Check if the application is in the maintenance status.' . PHP_EOL; // 第一个step

3_1. echo '10: Start session of this request.' . PHP_EOL; // 第三个step

5. echo '10: Verify csrf token when post request.' . PHP_EOL; // 第五个step

6.echo '10: Send Request to the Kernel, and Return Response.' . PHP_EOL; //第六个step

4. echo '10: Share the errors variable from response to the views.' . PHP_EOL; // 第四个step

3_2. echo '10: Close session of this response.' . PHP_EOL; // 第三个step

2. echo '10: Add queued cookies to the response.' . PHP_EOL; // 第二个step

经过上面的一步步分析,就能很清楚Laravel源码中Middleware的执行步骤了。再复杂的步骤只要一步步拆解,就很清晰每一步的逻辑,然后把步骤组装,就能知道全貌了。

总结:本文主要学习了Laravel的Middleware的源码,学习完后就知道没有什么神秘之处,只需要动手一步步拆解就行。后面再学习下Container的源码,到时见。

欢迎关注Laravel-China

RightCapital招聘Laravel DevOps


如果觉得我的文章对你有用,请随意赞赏

你可能感兴趣的

MuReinhard · 2016年11月25日

一周目看懂一半 应该是匿名函数特性还不熟 再来一次

回复

lx1036 作者 · 2016年11月25日

可以自己手写个小demo,这样看会好些。。多看几次就会了。。

回复

MuReinhard · 2016年11月25日

@lx1036 嗯 正在先按照你的demo写 先分析部分代码 一点点啃

回复

MuReinhard · 2016年11月25日

打开laravel里面看就是一个迷宫也是一个大宝库 去里面学思想 去composer里的开源项目学解决思路 我爱开源啊

回复

lx1036 作者 · 2016年11月25日

Laravel源码值得永久啃下去。学习模仿它的设计。

回复

MuReinhard · 2016年11月25日

@lx1036 看明白了 这个设计太妙了

回复

MuReinhard · 2016年11月25日

这么好的文章就是看的人少了点 我觉得比我目前看到的所谓源码分析的文章好得多

回复

lx1036 作者 · 2016年11月25日

你这么喜欢laravel,可以去看看laravel-china这个社区,https://laravel-china.org/。。觉得好帮忙多多推荐推荐喽,希望帮到更多的人。。

回复

471395320 · 2017年04月01日

很好的文章,豁然开朗。

回复

载入中...