> 得益于全局自定義異常的設計,驗證器的使用可以變得更加靈活。
* * * * *
### 驗證器基類
`goCheck` 方法,對客戶端傳遞的參數做校驗
~~~
use app\lib\exception\ParameterException;
use think\Request;
use think\Validate;
class BaseValidate extends Validate
{
/**
* 獲取客戶端傳遞的參數進行校驗
* @return bool
* @throws ParameterException 參數異常
*/
public function goCheck() {
$request = Request::instance();
$data = $request->param();
$result = $this->batch()->check($data);
if (!$result) {
throw new ParameterException([
'msg' => $this->getError()
]);
}
return true;
}
/**
* 必須是正整數
*/
protected function isPositiveInt($value, $rule, $data) {
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
return true;
} else {
return false;
}
}
/**
* 不能為空
*/
protected function isNotEmpty($value, $rule, $data) {
if (empty($value)) {
return false;
} else {
return true;
}
}
}
~~~
`ParameterException`的編碼如下:
~~~
class ParameterException extends BaseException
{
public $code = 400;
public $msg = '參數錯誤';
public $errCode = 10000;
}
~~~
* * * * *
使用的實例請看下一小節