thinkphp中间件handle方法是核心入口,必须返回response对象或调用$next($request);接收$request和$next参数,遵循洋葱模型,支持前置处理、后置处理及依赖注入。

ThinkPHP中间件的 handle 方法是中间件执行的核心逻辑入口,必须返回一个 Response 对象或调用 $next($request) 向下传递请求。
handle 方法的基本结构
该方法接收两个参数:$request(当前请求对象)和 $next(下一个中间件或最终控制器的闭包)。必须有返回值,否则请求会中断且无响应。
标准写法如下:
public function handle($request, \Closure $next)
{
// 前置处理:如日志、权限校验、请求过滤等
if ($request->isPost() && !captcha_check($request->post('captcha'))) {
return json(['code' => 400, 'msg' => '验证码错误']);
}
// 执行后续中间件或业务逻辑
$response = $next($request);
// 后置处理:如添加响应头、记录耗时、修改响应内容等
$response->header('X-Processed-By', 'AuthMiddleware');
return $response;
}
常见使用场景与写法要点
-
权限控制类中间件:校验登录态或角色,不满足条件直接返回响应,不调用
$next -
日志/性能监控中间件:在
$next前后记录时间,计算耗时并写入日志 - 请求预处理中间件:如统一解析 JSON 请求体、转换参数格式、设置请求上下文
-
响应修饰中间件:对
$response调用withCookie()、header()或content()修改输出
注意返回值和执行顺序
ThinkPHP 中间件采用“洋葱模型”——请求进来时逐层进入,响应返回时逐层出来。因此:
- 所有前置逻辑写在
$next($request)之前 - 所有后置逻辑写在
$next($request)之后,并基于其返回的$response操作 - 不能只写
$next($request)而不返回,必须显式return $next($request) - 若想终止流程(如未登录跳转),直接
return redirect('/login')或return json(...)即可
支持依赖注入的写法(TP6.1+)
如果中间件需要其他服务(如 Cache、Log),可在构造函数中声明,框架自动注入:
use think\cache\Cache;
use think\log\Log;
class ApiRateLimitMiddleware
{
protected $cache;
protected $log;
public function __construct(Cache $cache, Log $log)
{
$this->cache = $cache;
$this->log = $log;
}
public function handle($request, \Closure $next)
{
$ip = $request->ip();
$key = 'rate_limit:' . $ip;
$count = $this->cache->get($key, 0);
if ($count >= 100) {
return json(['code' => 429, 'msg' => '请求过于频繁']);
}
$this->cache->set($key, $count + 1, 60);
return $next($request);
}
}
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











