一、自定义验证层
目录结构
IDMustBePostiveInt 参数必须是正整数 参数验证层
<?php
namespace app\api\validate;
use think\Validate;
class IDMustBePostiveInt extends Validate
{
protected $rule = [
'id' => 'require|isPostiveInteger'
];
//field是字段名
protected function isPostiveInteger($value, $rule = '', $data = '', $field = ''){
if(is_numeric($value) && is_int($value + 0) && ($value + 0) > 0){
return true;
}else{
return $field.'必须是正整数';
}
}
}
controller层 banner接口
<?php
namespace app\api\controller\v1;
use app\api\validate\IDMustBePostiveInt;
use think\Validate;
class Banner
{
public function getBanner($id){
//验证器
$data = [
'id' => $id
];
$validate = new IDMustBePostiveInt();
$result = $validate -> batch()
-> check($data);
if($result){
//验证通过
echo '审核通过';
}else{
//验证失败
var_dump($validate -> getError());
}
}
}
二、 构建接口参数验证层
目录结构
controller控制器 banner接口
<?php
namespace app\api\controller\v1;
use app\api\validate\IDMustBePostiveInt;
use app\api\validate\TestValidate;
use think\Validate;
class Banner
{
public function getBanner($id){
(new IDMustBePostiveInt()) -> goCheck();
}
}
IDMustBePositiveInt 构建验证层
<?php
namespace app\api\validate;
class IDMustBePostiveInt extends BaseValidate
{
protected $rule = [
'id' => 'require|isPostiveInteger'
];
//field是字段名
protected function isPostiveInteger($value, $rule = '', $data = '', $field = ''){
if(is_numeric($value) && is_int($value + 0) && ($value + 0) > 0){
return true;
}else{
return $field.'必须是正整数';
}
}
}
BaseValidate 构建基层验证层
<?php
namespace app\api\validate;
use think\Exception;
use think\Request;
use think\Validate;
class BaseValidate extends Validate
{
public function goCheck(){
//获取http传入的参数
//对这些参数做校验
$request = Request::instance();
$params = $request -> param();
$result = $this -> check($params);
if(!$result){
$error = $this->getError();
throw new Exception($error);
}else{
return true;
}
}
}