资讯专栏INFORMATION COLUMN

Laravel学习笔记之Middleware源码解析

_Dreams / 875人阅读

摘要:学习笔记之已经聊过使用了来设计,看源码发现其巧妙用了和的一些数组函数来设计。开发环境内置函数和看源码之前,先看下这几个内置函数的使用。学习笔记之实例化源码解析已经聊过的实例化,得到中的变量,即的实例化对象。后面再学习下的源码,到时见。

说明:本文主要学习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变量,即IlluminateFoundationApplication的实例化对象。然后继续看下index.php的源码:

/**
 * @var AppHttpKernel $kernel
 */
$kernel = $app->make(IlluminateContractsHttpKernel::class);

$response = $kernel->handle(
    $request = IlluminateHttpRequest::capture()
);

$response->send();

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

首先从容器中解析出Kernel对象,对于AppHttpKernel对象的依赖:IlluminateFoundationApplication和IlluminateRoutingRouter,容器会自动解析。看下Kernel的构造函数:

    /**
     * Create a new HTTP kernel instance.
     *
     * @param  IlluminateContractsFoundationApplication  $app
     * @param  IlluminateRoutingRouter  $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);
        }
    }
    
    // IlluminateRoutingRouter内的方法
    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 = IlluminateHttpRequest::capture()

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

    /**
     * Handle an incoming HTTP request.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    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)函数执行了转换操作:把IlluminateHttpRequest对象转换成了IlluminateHttpResponse,然后通过Kernel的send()方法发送给客户端。同时,顺便触发了kernel.handled内核已处理请求事件。OK,重点关注下sendRequestThroughRouter($request)方法:

    /**
     * Send the given request through the middleware / router.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    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 = [
            "IlluminateFoundationBootstrapDetectEnvironment",
            "IlluminateFoundationBootstrapLoadConfiguration",
            "IlluminateFoundationBootstrapConfigureLogging",
            "IlluminateFoundationBootstrapHandleExceptions",
            "IlluminateFoundationBootstrapRegisterFacades",
            "IlluminateFoundationBootstrapRegisterProviders",
            "IlluminateFoundationBootstrapBootProviders",
        ];*/
        $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


给上完整的一个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

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/30467.html

相关文章

  • Laravel学习笔记bootstrap源码解析

    摘要:总结本文主要学习了启动时做的七步准备工作环境检测配置加载日志配置异常处理注册注册启动。 说明:Laravel在把Request通过管道Pipeline送入中间件Middleware和路由Router之前,还做了程序的启动Bootstrap工作,本文主要学习相关源码,看看Laravel启动程序做了哪些具体工作,并将个人的研究心得分享出来,希望对别人有所帮助。Laravel在入口index...

    xiaoxiaozi 评论0 收藏0
  • Laravel学习笔记Session源码解析(上)

    摘要:然后中间件使用方法来启动获取实例,使用类来管理主要分为两步获取实例,主要步骤是通过该实例从存储介质中读取该次请求所需要的数据,主要步骤是。 说明:本文主要通过学习Laravel的session源码学习Laravel是如何设计session的,将自己的学习心得分享出来,希望对别人有所帮助。Laravel在web middleware中定义了session中间件IlluminateSess...

    NervosNetwork 评论0 收藏0
  • Laravel学习笔记Filesystem源码解析(下)

    摘要:源码解析这个类的源码主要就是文件的操作和文件属性的操作,而具体的操作是通过每一个实现的,看其构造函数看以上代码知道对于操作,实际上是通过的实例来实现的。可以看下的使用上文已经说了,使得对各种的操作变得更方便了,不管是还是得。 说明:本文主要学习下LeagueFlysystem这个Filesystem Abstract Layer,学习下这个package的设计思想和编码技巧,把自己的一...

    Luosunce 评论0 收藏0
  • Laravel学习笔记Decorator Pattern

    摘要:把和拼接在一起的场所是,所以需要造一个类,在其内部实现对的操作中实现了把原有的进过个的装饰后得到的新的,新的还是的实现,还是原来的物种。 说明:Laravel中Middleware的实现主要利用了Decorator Pattern的设计,本文主要先学习下Decorator Pattern如何实现,为后面学习Middleware的设计做个铺垫。Decorator Pattern和Adap...

    dendoink 评论0 收藏0
  • Laravel学习笔记Route,Middleware和Controller参数传递

    摘要:本文主要学习总结下间参数传递。开发时经常碰到类似场景有时需要在中读取中设置的和,有时也需要在中读取中设置的参数。总结下这几个知识点,便于查阅。 本文主要学习总结下Route,Middleware,Controller间参数传递。开发时经常碰到类似场景:有时需要在Middleware中读取Route中设置的middleware parameter和route parameter,有时也需...

    zhangyucha0 评论0 收藏0

发表评论

0条评论

_Dreams

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<