记录:
1,中间件的作用:中间件主要用于拦截或过滤应用的HTTP请求,并进行必要的业务处理。
2,注意:
- 中间件的入口执行方法必须是handle方法,而且第一个参数是Request对象,第二个参数是一个闭包
-
中间件handle方法的返回值必须是一个Response对象。
-
在某些需求下,可以使用第三个参数传入额外的参数。
3,创建中间件:这个指令会 application/http/middleware
目录下面生成一个 Check 中间件。
php think make:middleware Check
<?php
namespace app\http\middleware;
class Check
{
public function handle($request, \Closure $next)
{
if ($request->param('name') == 'think') {
return redirect('index/think');
}
return $next($request);
}
}
4,使用示例:
a/ 创建中间件 InAppCheck
<?php
namespace app\http\middleware;
/**
* 访问环境检查,是否是微信或支付宝等
*/
class InAppCheck
{
public function handle($request, \Closure $next)
{
if(preg_match('~micromessenger~i',$request->header('user-agent'))){
$request->InApp = 'WeChat';
}else if(preg_match('~alipay~i', $request->header('user-agent'))){
$request->InApp = 'Alipay';
}else{
$request->InApp = 'other';
}
return $next($request);
}
}
b/ 在模块module 下添加 middleware.php,例如/path/application/index/middleware.php
<?php
return [
app\http\middleware\InAppCheck::class,
];
c/ 然后在controller
中可以通过$this->request->InApp
获取相关的值,控制器需继承Controller
public function index()
{
$InApp = $this->request->InApp;
echo '<pre>';print_r($InApp);
}
5,注册中间件:
a/ 注册路由中间件
//1,注册路由中间件
//传完整类名
Route::rule('test','test/index/index')
->middleware(app\http\middleware\InAppCheck::class);
//传'InAppCheck',会自动在application/http/middleware目录下找到InAppCheck类
// Route::rule('test','test/index/index')
// ->middleware('InAppCheck');
//支持注册多个
// Route::rule('test','test/index/index')
// ->middleware(['Auth', 'InAppCheck']);
//2,如果需要传入额外参数给中间件,可以使用
Route::rule('test','test/index/index')
->middleware('Ckeck:administrator');
//或使用常量方式
// Route::rule('test','test/index/index')
// ->middleware(Ckeck::class,'administrator');
<?php
namespace app\test\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
$InApp = $this->request->InApp;
echo '<pre>';print_r($InApp);
return '测试通过注册路由中间件,获取相关值';
}
}
b/ 全局中间件
在应用目录(/path/application)下面定义middleware.php
文件,使用下面的方式:
<?php
return [
'InAppCheck',
[Ckeck::class,'adminni'],//传参
\app\http\middleware\Auth::class,//完整路径
];
c/ 模块中间件
在模块module 下添加 middleware.php,例如/path/application/index/middleware.php,定义方式和应用中间件定义一样,只是只会在该模块下面生效。
d/ 控制器中间件
<?php
namespace app\test\controller;
use think\Controller;
class Index extends Controller
{
//控制器定义中间件
protected $middleware = ['app\http\middleware\InAppCheck::class'];
//设置控制器中间件的生效操作(方法)
// protected $middleware = [
// 'app\http\middleware\InAppCheck::class' => ['except' => ['hello'] ],
// 'app\http\middleware\InAppCheck::class' => ['only' => ['hello'] ],
// ];
public function index()
{
$InApp = $this->request->InApp;
echo '<pre>';print_r($InApp);
return '测试控制器定义中间件,获取相关值';
}
}
6,中间件向控制器传参:
<?php
namespace app\http\middleware;
class Hello
{
public function handle($request, \Closure $next)
{
//可以通过给请求对象赋值的方式传参给控制器(或者其它地方)
//注意:传递的变量名称不要和param变量有冲突。
$request->hello = 'ThinkPHP';
return $next($request);
}
}