1.定义公共验证类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->error;
throw new Exception($error);
}
else{
return true;
}
}
}
~~~
2.把IDMustBePostiveInt 继承公共类
~~~
<?php
namespace app\api\validate;
use think\Validate;
class IDMustBePostiveInt extends BaseValidate
{
protected $rule = [
'id' => 'require|isPositiveInteger'
];
protected function isPositiveInteger($value, $rule = '',
$data = '', $field = '')
{
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
return true;
}
else{
return $field.'必须是正整数';
}
}
}
~~~
3.banner.php代码
~~~
<?php
namespace app\api\controller\v1;
use app\api\validate\IDMustBePostiveInt;
class Banner{
//获取指定id的banner信息
public function getBanner($id)
{
(new IDMustBePostiveInt())->goCheck();
echo "123";
}
}
~~~
结果:
![](https://box.kancloud.cn/c25587d069a7ec0059643e71fe94a8b9_1310x840.png)