laravel中间件的实现原理

中间件的实现原理

运用 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);
posted @ 2019-09-06 10:07  柠檬v不萌  阅读(671)  评论(0编辑  收藏  举报