ThinkPHP5.1x的中间件,其核心还是闭包函数的应用,来实现“责任链”模式:
模拟代码:
'; }}//中间件class Before1 { public function handle($request, Closure $next) { echo 'before1'; //业务逻辑,注意前置与后置中间件业务逻辑代码的位置 return $next($request); }}//中间件class Before2 { public function handle($request, Closure $next) { echo 'before2'; return $next($request); }}//中间件class After1 { public function handle($request, Closure $next) { $response = $next($request); echo 'after1'; //业务逻辑,注意前置与后置中间件业务逻辑代码的位置 return $response; }}//中间件class After2 { public function handle($request, Closure $next) { $response = $next($request); echo 'after2'; return $response; }}class Middleware { public static $queue; //中间件队列 public static function init() { //模拟的中间件,数量任意添加 self::$queue[] = [[After1::class, 'handle'], null]; self::$queue[] = [[After2::class, 'handle'], null]; self::$queue[] = [[Before1::class, 'handle'], null]; self::$queue[] = [[Before2::class, 'handle'], null]; //模拟的控制器 self::$queue[] = [[Controller::class, 'index'], null]; } //调用中间件 public static function dispatch($request) { call_user_func(self::resolve(), $request); } //返回闭包函数 public static function resolve(){ return function($request){ $middleware = array_shift(self::$queue); if ($middleware != null) { list($call, $param) = $middleware; call_user_func_array($call, [$request, self::resolve()]); //执行中间件 } }; }}$request = "模拟的request对象";Middleware::init();Middleware::dispatch($request);