<?phpclass MiddlewareStack {private $middlewares = [];private $request;private $response;/*** 添加中间件到堆栈** @param callable $middleware 中间件函数,接受请求、响应和下一个中间件作为参数*/public function add(callable $middleware){$this->middlewares[] = $middleware;}/*** 设置请求和响应处理函数** @param callable $request 请求处理函数,无参数,返回一个请求对象或数据* @param callable $response 响应处理函数,接受请求处理结果作为参数,返回最终响应*/public function setHandlers(callable $request, callable $response){$this->request = $request;$this->response = $response;}/*** 处理请求,通过中间件堆栈** @return mixed 响应结果*/public function handle(){$next = function ($requestData) use (&$next) {// 如果没有更多的中间件,调用最终的响应处理函数if (empty($this->middlewares)) {return call_user_func($this->response, $requestData);}// 取出下一个中间件并调用$middleware = array_shift($this->middlewares);return $middleware($requestData, $this->response, $next);};// 从第一个中间件开始处理$requestData = call_user_func($this->request);return $next($requestData);} }// 示例中间件:身份验证 function authMiddleware($requestData, $response, $next) {// 模拟身份验证检查if (!isset($requestData['user'])) {return "Unauthorized"; // 或者返回一个适当的 HTTP 响应 }return $next($requestData); }// 示例中间件:日志记录 function loggingMiddleware($requestData, $response, $next) {$startTime = microtime(true);$responseData = $next($requestData);$endTime = microtime(true);// 这里可以记录日志,例如使用 monolog 或其他日志库echo "Request took " . ($endTime - $startTime) . " seconds\n";return $responseData; }// 示例请求处理函数 function requestFunction() {// 模拟一个请求,例如从 $_GET, $_POST, 或其他来源获取数据return ['user' => 'john_doe', // 模拟已验证的用户// 其他请求数据... ]; }// 示例响应处理函数 function responseFunction($requestData) {// 处理请求数据并生成响应return "Hello, " . $requestData['user'] . "!"; }// 使用中间件 $middlewareStack = new MiddlewareStack(); $middlewareStack->add(authMiddleware); $middlewareStack->add(loggingMiddleware); $middlewareStack->setHandlers(requestFunction, responseFunction);// 处理请求 $response = $middlewareStack->handle(); echo $response;