中间件的实现原理

运用 array_reduce 以及 call_user_func 实现

interface middleware
{
    public static function handle(closure $next);
}

class verfiycsrftoekn implements milldeware{    
    public static function handle(closure $next)    {        
        echo '验证csrf token <br>';        
        $next();    
    }
}

class verfiyauth implements milldeware{
    public static function handle(closure $next)    {        
        echo '验证是否登录 <br>';        
        $next();    
    }
}

class setcookie implements milldeware{    
    public static function handle(closure $next)    {        
        $next();        
        echo '设置cookie信息!';    
    }
}

$handle = function () {    
    echo '当前要执行的程序!';
};

$pipe_arr = [ 'verfiycsrftoekn', 'verfiyauth', 'setcookie', ];

$callback = array_reduce($pipe_arr, function ($stack, $pipe) {
    return function () use ($stack, $pipe) {
        return $pipe::handle($stack);
    };
}, $handle);

call_user_func($callback);