ThinkPHP 8.0 强制中间件实现 MiddlewareInterface 接口且 handle() 返回 \think\Response;仅支持 app/middleware.php 返回 ::class 常量数组;路由/控制器绑定须用完整类名或 ::class;中间件中禁用 session() 和 $request->param(),应改用 $request->post()、$request->get() 或 withAttribute()。

中间件类定义必须实现接口并声明返回类型
ThinkPHP 8.0 强制要求所有中间件类实现 think\contract\MiddlewareInterface 接口,且 handle() 方法必须明确标注返回类型为 \think\Response。TP6.0.16 中常见的无接口、无类型声明写法在 TP8 下会触发 PHP 8.1+ 的 TypeError 或容器反射失败。
需将原写法:
namespace app\middleware;
class Auth {
public function handle($request, \Closure $next) {
return $next($request);
}
}
改为:
namespace app\middleware;
use think\contract\MiddlewareInterface;
class Auth implements MiddlewareInterface {
public function handle($request, \Closure $next): \think\Response {
return $next($request);
}
}
全局中间件注册路径与格式严格受限
TP8 仅识别 app/middleware.php 文件,且该文件必须直接返回一个类名数组,不支持 use 语句、闭包、相对命名空间字符串。
PHP 8.5.12 RC 1 候选版修复 BZ2、DOM、PDO、Opcache/JIT 和扩展内存安全问题,改进 Unicode 字素处理、URL 解析、TLS 流状态、信号分发及会话错误处理。
立即学习“PHP免费学习笔记(深入)”;
- ✅ 正确:返回带反斜杠的
::class常量,如\app\middleware\Auth::class - ❌ 错误:
'app\middleware\Auth'(缺反斜杠,导致类解析失败) - ❌ 错误:
use app\middleware\Auth; return [Auth::class];(use在配置文件中被忽略) - ❌ 错误:
return [function() { ... }](TP8 禁用闭包中间件)
路由与控制器级中间件绑定方式变更
TP6.0.16 支持字符串别名(如 ->middleware('auth')),TP8 已完全废弃,只接受完整命名空间类名或 ::class 常量。
- 路由绑定示例:
Route::get('api/user', 'User@index')->middleware(\app\middleware\Auth::class) - 控制器内注册需在
initialize()中调用:$this->middleware->add(\app\middleware\Auth::class) - 多中间件传数组:
->middleware([\app\middleware\Auth::class, \think\middleware\AllowCrossDomain::class])
中间件内不可直接使用 session() 和 $request->param()
TP8 中间件执行时机提前,session() 助手函数尚未初始化,$request->param() 会合并 POST/GET 导致逻辑错乱。
应改用:
-
$request->post()或$request->get()显式获取参数 -
$request->getContent()获取原始请求体(如 JSON) - 需传递上下文数据时,用
$request->withAttribute('key', $value),后续控制器可通过$this->request->getAttribute('key')获取


















