Thinkphp5.1 中间件如何使用?
1.中间件的作用:
在请求到达应用层之前,对请求携带的头信息,参数信息,url路径等进行操作处理,提高代码复用性,简化应用层的代码
2.脚手架命令行定义中间件:
php think make:middleware Check
会生成文件:\application\http\middleware\Check.php
在Check.php 中的入口方法 handle 中定义处理逻辑,并调用回调函数$next 参数$request返回数据
<?php
namespace app\http\middleware;
use think\Request;
class Check
{
public function handle(Request $request, \Closure $next)
{
$request->setHost('114.114.114.114');
return $next($request);
}
}
3.注册中间件:
在应用目录application或其他模块目录下创建middleware.php文件,并在文件中返回上一步定义的中间件类
<?php
return [
\app\http\middleware\Check::class,
];
4.在上一步注册过中间件的应用或模块中的控制器中使用中间件:
1.控制器继承基控制器:think\Controller
2.定义属性:$middleware 设置生效的中间件
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
//设置中间件
protected $middleware = ['Check'];
//服务大厅入口
public function index()
{
var_dump($this->request);die;
return $this->fetch();
}
}
5.在路由规则中使用中间件:
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 20062018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\facade\Route;
Route::group('customer', function() {
Route::get('login', '@customer/Login/index');
Route::post('sendMsg', '@customer/Message/send')->middleware(['Check']);
});
网友评论