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";
}
}
~~~
結果:
