0
点赞
收藏
分享

微信扫一扫

thinkphp5.1全局验证层封装

玉新行者 2022-10-14 阅读 92


1.在很多场景下我们都要对表单提交的数据进行验证,那么如何实现一个验证的重复使用呢,那就让我们来封装一个全局的验证层吧!首先我们创建validate,如下图

thinkphp5.1全局验证层封装_数据

这样,我们文件夹下就出现了一个文件夹。

thinkphp5.1全局验证层封装_字段名_02

2.我们来编写CeshiValidate.php

<?php

namespace app\common\validate;

use think\Validate;

class CeshiValidate extends BaseValidate
{
/**
* 定义验证规则
* 格式:'字段名' => ['规则1','规则2'...]
*
* @var array
*/
protected $rule = [
'username'=>'require',
'email'=>'require|email',
];

/**
* 定义错误信息
* 格式:'字段名.规则名' => '错误信息'
*
* @var array
*/
protected $message = [
'username.require'=>'用户名不能为空',
'email.require'=>'邮箱不能为空',
'email.email'=>'邮箱格式不正确'
];

// 验证场景
protected $scene = [
'login'=>['username','email'],
];
}

3.由于CeshiValidate.php继承BaseValidate类,所以,BaseValidate.php代码如下所示。

<?php 
namespace app\common\validate;
use think\Validate;
use app\lib\exception\BaseException;

/**
*
*/
class BaseValidate extends Validate
{

public function goCheck($scene='')
{
// 获取用户请求过来的所有数据
$param = request()->param();
// 开始验证
if(empty($param)){
$check = $this->check($param);
}else{
$check = $this->scene($scene)->check($param);
}
if(!$check){
throw new BaseException(['msg'=>$this->getError(),'errorCode'=>10000,'code'=>400]);
}
return true;
}
}
?>

4. 那么我们如何调用呢,请看下面代码。

<?php

namespace app\Index\controller;

use think\Controller;
use think\Request;
use app\lib\exception\BaseException;
use app\common\validate\CeshiValidate;

class Index extends Controller
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
(new CeshiValidate())->goCheck('login');
}
}

简单几步,我们封装了验证类,以后不用每次都重复写了。


举报

相关推荐

0 条评论