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