slim 4 中间件必须实现 middlewareinterface 接口,使用类而非闭包;process() 方法需接收 serverrequestinterface 和 requesthandlerinterface 并返回 responseinterface,且必须调用 $handler->handle($request) 继续管道。

Slim 4 的中间件必须实现 MiddlewareInterface
PSR-15 要求中间件是一个类,且必须实现 MiddlewareInterface,不能是闭包或函数。Slim 4 不再接受 function ($req, $res, $next) 这种老式写法——直接报错:TypeError: Argument 1 passed to Slim\App::add() must be an instance of Psr\Http\Server\MiddlewareInterface。
实操建议:
- 用
class MyAuthMiddleware implements MiddlewareInterface定义中间件 -
process()方法必须接收ServerRequestInterface和RequestHandlerInterface,返回ResponseInterface - 别忘了在
process()中调用$handler->handle($request)向下传递请求,否则管道中断
如何正确注册中间件:全局、路由组、单个路由三者区别
注册位置决定作用域,也影响执行顺序。Slim 4 的中间件执行是“外层先入、内层后出”的洋葱模型,但注册点不同,包裹关系不同。
实操建议:
- 全局中间件(
$app->add(new MyLoggerMiddleware()))会包裹所有路由,包括 404 - 路由组中间件(
$app->group('/api', function () { ... })->add(new JwtMiddleware()))只对组内路由生效 - 单个路由中间件(
$app->get('/admin', ...)->add(new AdminOnlyMiddleware()))最内层,最后执行、最先响应 - 注意:多个
add()调用顺序就是执行顺序(从上到下),不是从下到上
RequestHandlerInterface 不是 Response,别试图直接返回数组或字符串
常见错误是把 process() 当成控制器,直接 return ['error' => 'unauthorized'] 或 echo 'forbidden',结果抛出 TypeError: Return value of MyMiddleware::process() must be an instance of Psr\Http\Message\ResponseInterface。
实操建议:
- 必须用
$response = $responseFactory->createResponse(401)创建响应对象(可通过依赖注入获取ResponseFactoryInterface) - 写 JSON 响应时,记得设置头:
$response->withHeader('Content-Type', 'application/json')->getBody()->write(json_encode([...])) - 不要复用传入的
$response参数——它只是占位符,实际应由工厂创建新实例
中间件里拿不到 $app 或容器?用 ContainerInterface 注入
Slim 4 默认不把 $app 实例传进中间件,想访问数据库、配置或服务,不能靠全局变量或静态调用——那会破坏可测试性,也容易引发循环依赖。
实操建议:
- 在中间件构造函数中声明
public function __construct(ContainerInterface $container) - 通过
$this->container->get('db')或$this->container->get(PDO::class)获取服务 - 避免在
process()里做容器查找,构造时查好并缓存为属性,提升性能 - 如果容器未注入成功,检查
dependencies.php是否正确定义了该中间件的工厂或实例
$handler->handle($request) 或返回错类型,整个请求就静默失败——连错误页都不会出来。php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











