💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 验证器的位置 ![](https://img.kancloud.cn/93/7d/937da57cb6b0ab149b98ab088ff96898_362x597.png) 继承**BaseValidate**验证器 ``` ~~~ /** * Class BaseValidate * 验证类的基类 */ class BaseValidate extends Validate { /** * 检测所有客户端发来的参数是否符合验证类规则 * 基类定义了很多自定义验证方法 * 这些自定义验证方法其实,也可以直接调用 * @throws ParameterException * @return true */ public function goCheck() { //必须设置contetn-type:application/json $request = Request::instance(); $params = $request->param(); $params['token'] = $request->header('token'); if (!$this->check($params)) { $exception = new ParameterException( [ // $this->error有一个问题,并不是一定返回数组,需要判断 'msg' => is_array($this->error) ? implode( ';', $this->error) : $this->error, ]); throw $exception; } return true; } /** * @param array $arrays 通常传入request.post变量数组 * @return array 按照规则key过滤后的变量数组 * @throws ParameterException */ public function getDataByRule($arrays) { if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) { // 不允许包含user_id或者uid,防止恶意覆盖user_id外键 throw new ParameterException([ 'msg' => '参数中包含有非法的参数名user_id或者uid' ]); } $newArray = []; foreach ($this->rule as $key => $value) { $newArray[$key] = $arrays[$key]; } return $newArray; } protected function isPositiveInteger($value, $rule='', $data='', $field='') { if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) { return true; } return $field . '必须是正整数'; } protected function isNotEmpty($value, $rule='', $data='', $field='') { if (empty($value)) { return $field . '不允许为空'; } else { return true; } } //没有使用TP的正则验证,集中在一处方便以后修改 //不推荐使用正则,因为复用性太差 //手机号的验证规则 protected function isMobile($value) { $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^'; $result = preg_match($rule, $value); if ($result) { return true; } else { return false; } } // // 令牌合法并不代表操作也合法 // // 需要验证一致性 // protected function isUserConsistency($value, $rule, $data, $field) // { // $identities = getCurrentIdentity(['uid', 'power']); // extract($identities); // // // 如果当前令牌是管理员令牌,则允许令牌UID和操作UID不同 // if ($power == ScopeEnum::Super) { // return true; // } // else { // if ($value == $uid) { // return true; // } // else { // throw new TokenException([ // 'msg' => '你怎么可以用自己的令牌操作别人的数据?', // 'code' => 403, // 'errorCode' => '10003' // ]); // } // } // } } ~~~ ``` ## 其次在 其他验证器里面就继承就行了 如:: ~~~ class TokenGet extends BaseValidate { protected $rule = [ 'code' => 'require|isNotEmpty' ]; protected $message=[ 'code' => '没有code还想拿token?做梦哦' ]; } ~~~ 或者 ``` ~~~ class AddressNew extends BaseValidate { // 为防止欺骗重写user_id外键 // rule中严禁使用user_id // 获取post参数时过滤掉user_id // 所有数据库和user关联的外键统一使用user_id,而不要使用uid protected $rule = [ 'name' => 'require|isNotEmpty', 'mobile' => 'require|isMobile', 'province' => 'require|isNotEmpty', 'city' => 'require|isNotEmpty', 'country' => 'require|isNotEmpty', 'detail' => 'require|isNotEmpty', ]; } ~~~ ``` ## 控制器里面调用 ``` ~~~ $validate = new IDMustBePositiveInt(); $validate->goCheck(); ~~~ ```