php laravel请求处理管道(装饰者模式)

laravel的中间件使用了装饰者模式。好比,验证维护模式,cookie加密,开启会话等等。这些处理有些在响应前,有些在响应以后,使用装饰者模式动态减小或增长功能,使得框架可扩展性大大加强。

接下来简单举个例子,使用装饰者模式实现维护Session实现。

没有使用装饰者模式,须要对模块(WelcomeController::index方法)进行修改。

    class WelcomeController
    {
        public function index()
        {
            echo 'session start.', PHP_EOL;
            echo 'hello!', PHP_EOL;
            echo 'session close.', PHP_EOL;
        }
    }

使用装饰者模式,$pipeList表示须要执行的中间件数组。关键在于使用了array_reduce函数(http://php.net/manual/zh/function.array-reduce.php)

    class WelcomeController
    {
        public function index()
        {
            echo 'hello!', PHP_EOL;
        }
    }
    interface Middleware
    {
        public function handle(Closure $next);
    }
    class Seesion implements Middleware
    {
        public function handle(Closure $next)
        {
            echo 'session start.', PHP_EOL;
            $next();
            echo 'session close.', PHP_EOL;
        }
    }
    $pipeList = [
        "Seesion",
    ];
     
    function _go($step, $className)
    {
        return function () use ($step, $className) {
            $o = new $className();
            return $o->handle($step);
        };
    }
     
    $go = array_reduce($pipeList, '_go', function () {
        return call_user_func([new WelcomeController(), 'index']);
    });
    $go();

php

相关文章
相关标签/搜索