Laravel中间件实现原理

来源:互联网 发布:linux 串口输出重定向 编辑:程序博客网 时间:2024/06/05 10:18

1. 什么是中间件?

对于一个Web应用来说,在一个请求真正处理前,我们可能会对请求做各种各样的判断,然后才可以让它继续传递到更深层次中。而如果我们用if else这样子来,一旦需要判断的条件越来越来,会使得代码更加难以维护,系统间的耦合会增加,而中间件就可以解决这个问题。我们可以把这些判断独立出来做成中间件,可以很方便的过滤请求。

2. Laravel中的中间件

在Laravel中,中间件的实现其实是依赖于Illuminate\Pipeline\Pipeline这个类实现的,我们先来看看触发中间件的代码。很简单,就是处理后把请求转交给一个闭包就可以继续传递了。

    public function handle($request, Closure $next) {        //do something for $request        return $next($request);    }

3. 中间件内部实现

上面说道,中间件是靠Pipeline来实现的,它的调用在Illuminate\Routing\Router中

    return (new Pipeline($this->container))        ->send($request)        ->through($middleware)        ->then(function ($request) use ($route) {            return $this->prepareResponse(                $request,                $route->run($request)            );    });

可以看到,中间件执行过程调用了三个方法。再来看看这三个方法的代码:

send方法

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

其实send方法没做什么事情,就是设置了需要在中间件中流水处理的对象,在这里就是HTTP请求实例。

through方法

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

through方法也很简单,就是设置一下需要经过哪些中间件处理。

then方法

真正难懂的来了,then方法代码很简洁,但是要理解可不容易。

public function then(Closure $destination){   //then方法接受一个闭包作为参数,然后经过getInitialSlice包装,而getInitialSlice返回的其实也是一个闭包,如果还不知道什么是闭包先去看PHP文档   $firstSlice = $this->getInitialSlice($destination);   //反转中间件数组,主要是利用了栈的特性,用处接下来再说   $pipes = array_reverse($this->pipes);   //这个call_user_func先不要看,它其实就是执行了一个array_reduce返回的闭包   return call_user_func(       //array_reduce来用回调函数处理数组。其实arrary_reduce什么事情都没干,就是包装闭包然后移交给call_user_func来执行       array_reduce($pipes, $this->getSlice(), $firstSlice), $this->passable   );}

然后就没有然后了,这样就过完了所有中间件,是不是很优雅?
由于aray_reduce的第二个参数需要一个函数,我们这里重点看看getSlice()方法的源码

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

看到可能会很头晕,闭包返回闭包的。简化一下就是getSlice()返回一个函数A,而函数A又返回了函数B。为什么要返回两个函数呢?因为我们中间在传递过程中是用next(request)来传递对象的,而next(request)这样的写法就表示是执行了这个闭包,这个闭包就是函数A,然后返回函数B,可以给下一个中间件继续传递。

再来简化一下代码就是:

//这里的$stack其实就是闭包,第一次遍历的时候会传入$firstSlice这个闭包,以后每次都会传入下面的那个function; 而$pipe就是每一个中间件array_reduce($pipes, function ($stack, $pipe) {    return function ($passable) use ($stack, $pipe) {    };}, $firstSlice);

再来看这一段代码:

//判断是否为闭包,这里就是判断中间件形式是不是闭包,是的话直接执行并且传入$passable[请求实例]和$stack[传递给下一个中间件的闭包],并且返回if ($pipe instanceof Closure) {   return call_user_func($pipe, $passable, $stack);//不是闭包的时候就是形如这样Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode执行}  else {   //解析,把名称返回,这个$parameters看了许久源码还是看不懂,应该是和参数相关,不过不影响我们的分析   list($name, $parameters) = $this->parsePipeString($pipe);   //从容器中解析出中间件实例并且执行handle方法    return call_user_func_array([$this->container->make($name), $this->method],        //$passable就是请求实例,而$stack就是传递的闭包        array_merge([$passable, $stack], $parameters)    );}

再看一张图片:

Laravel中间件原理

每一次迭代传入上一次的闭包和需要执行的中间件,由于反转了数组,基于栈先进后出的特性,所以中间件3第一个被包装,中间件1就在最外层了。要记得,arrary_reduce他不执行中间件代码,而是包装中间件。
看到这里应该明白了,array_reduce最后会返回func3,那么call_user_func(func3,$this->passable)实际就是

return call_user_func($middleware[0]->handle, $this->passable, func2);

而我们的中间件中的handle代码是:

public function handle($request, Closure $next) {    return $next($request);}

这里就相当于return func2(request)request就是经过上一个中间件处理过的。所以正果中间件的过程就完了,理解起来会有点绕,只要记得最后是由最外面的call_user_func来执行中间件代码的.

声明:本文转载于http://www.jianshu.com/p/f70612661422

0 0
原创粉丝点击