ThinkPHP5.1x的中间件,其核心还是闭包函数的应用,来实现“责任链”模式:
模拟代码:
<?php //模拟的控制器 class Controller { public function index($request) { echo '控制器方法体',$request,'<br>'; } } //中间件 class Before1 { public function handle($request, Closure $next) { echo 'before1<br>'; //业务逻辑,注意前置与后置中间件业务逻辑代码的位置 return $next($request); } } //中间件 class Before2 { public function handle($request, Closure $next) { echo 'before2<br>'; return $next($request); } } //中间件 class After1 { public function handle($request, Closure $next) { $response = $next($request); echo 'after1<br>'; //业务逻辑,注意前置与后置中间件业务逻辑代码的位置 return $response; } } //中间件 class After2 { public function handle($request, Closure $next) { $response = $next($request); echo 'after2<br>'; 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);