可以通过命令行指令快速生成中间件
php think make:middleware Check # check表示中间件类名称
这个指令会 application/http/middleware目录下面生成一个Check中间件
<?php
namespace app\http\middleware;
class Check
{
public function handle($request, \Closure $next)
{
if ($request->param('name') == 'think') {
return redirect('http://www.baidu.com');
}
return $next($request);
}
}
中间件的入口执行方法必须是handle方法,而且第一个参数是Request对象,第二个参数是一个闭包
中间件handle方法的返回值必须是一个Response对象。
在这个中间件中我们判断当前请求的name参数等于think的时候进行重定向处理。否则,请求将进一步传递到应用中。要让请求继续传递到应用程序中,只需使用 $request 作为参数去调用回调函数 $next 。
中间件是有了 但是我们接下来需要注册路由中间件
V5.1.7+版本,我们可以直接在应用配置目录下的middleware.php中 /config/middleware.php配置文件中先预定义中间件(其实就是增加别名标识),例如
接下来才是注册路由中间件: 找到/route/route.php文件 在里面注册路由:
Route::rule('index/:name','index/index/index')->middleware('check');
然后访问 xx.cn/index/think 这个时候路由中间件就会起作用 直接蹦到百度去了
手册当中还有其他的用法 可以详细去了解 https://www.kancloud.cn/manual/thinkphp5_1/564279
另外我们还可以从中间件往控制器当中传参:
<?php namespace app\http\middleware; class Check { public function handle($request, \Closure $next) { $request->hello='xiaohu'; //直接这么写就行 if ($request->param('name') == 'think') { return redirect('http://www.baidu.com'); } return $next($request); } }
然后在控制器当中正常接收即可:
<?php namespace app\index\controller; use think\Controller; class Index extends Controller { public function index() { echo $this->request->hello;//正常接收中间件传递的参数 $name = $this->request->param('name'); echo $name;die; } }