1.验证器中BaseValidate.php
~~~
<?php
namespace app\api\validate;
use app\lib\exception\ParameterException;
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->batch()->check($params);
if(!$result){
$e =new ParameterException();
$e->msg=$this->error;
throw $e;
//$error = $this->error;
//throw new Exception($error);
}
else{
return true;
}
}
}
~~~
2.BaseException.php文件
~~~
<?php
namespace app\lib\exception;
use think\Exception;
/**
* Class BaseException
* 自定义异常类的基类
*/
class BaseException extends Exception
{
public $code = 400;
//public $msg = 'invalid parameters';
public $msg = '参数错误';
public $errorCode = 999;
/**
* 构造函数,接收一个关联数组
* @param array $params 关联数组只应包含code、msg和errorCode,且不应该是空值
*/
public function __construct($params=[])
{
if(!is_array($params)){
return;
}
if(array_key_exists('code',$params)){
$this->code = $params['code'];
}
if(array_key_exists('msg',$params)){
$this->msg = $params['msg'];
}
if(array_key_exists('errorCode',$params)){
$this->errorCode = $params['errorCode'];
}
}
}
~~~
验证器IDMustBePostiveInt.php中
~~~
<?php
namespace app\api\validate;
use think\Validate;
class IDMustBePostiveInt extends BaseValidate
{
protected $rule = [
'id' => 'require|isPositiveInteger',
'num'=>'in:1,2,3'
];
protected function isPositiveInteger($value, $rule = '',
$data = '', $field = '')
{
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
return true;
}
else{
return $field.'必须是正整数';
}
}
}
~~~
![](https://box.kancloud.cn/8af1f2422de4ba88499e0b079b1680bf_1357x605.png)