统一验证层的封装和全局异常抛出

开发过程中很有必要对数据进行验证.封装一个验证基类,进行统一处理,撸起代码更加方便,代码更加简洁.
全局异常的抛出,很适合api接口

这里以我以前做过的一个项目为例:

1.封装验证基类

namespace app\common\validate;

use think\exception\HttpException;
use think\Request;
use think\Validate;

/**
 * Class BaseValidate
 * 验证类的基类
 */
class BaseValidate extends Validate
{
    /**
     * 检测所有客户端发来的参数是否符合验证类规则
     * 基类定义了很多自定义验证方法
     * 这些自定义验证方法其实,也可以直接调用
     * @throws ParameterException
     * @return true
     */
    public function goCheck()
    {
        //必须设置contetn-type:application/json
        $request = Request::instance();
        $params = $request->param();


        if (!$this->check($params)) {
            $msg=is_array($this->error) ? implode(';', $this->error) : $this->error;
            $exception = new HttpException(206, $msg);
            throw $exception;
        }
        return true;
    }

    public function getCheck($params)
    {
        if (!$this->check($params)) {
            $msg=is_array($this->error) ? implode(';', $this->error) : $this->error;
            $exception = new HttpException(206, $msg);
            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 HttpException(288,'参数中包含有非法的参数名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|9)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    protected function isCartype($value)
    {

        $rule = ['1','2','3','4','5'];
        $result = in_array($value, $rule);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /*
     *不需要验证规则
     */
    protected function nova($value)
    {
        return true;
    }
}

2.在应用目录下面新建一个文件夹validate

这里面放所有的验证类


image.png

3.使用方法

 (new DriverVa())->goCheck();

如果感觉麻烦,直接这样也可以

        $singleRu = [
            'mobile' => 'isMobile',
            'checkcode' => 'require',
        ];
        $validate = new BaseValidate($singleRu);

里面有自动异常抛出,这样就不用每次判断返回值了.

全局异常抛出

1.配置文件(对异常处理接管)

 'exception_handle'       => '\app\lib\exception\Http',

2.异常抛出类(很适合API接口)

namespace app\lib\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\Request;
class Http extends Handle
{

    public function render(\Exception $e)
    {
        if ($e instanceof HttpException) {
            $statusCode = $e->getStatusCode();
        }

        if (!isset($statusCode)) {
            $statusCode = 280;
        }
        $request = Request::instance();
        $result = [
            'code' => $statusCode,
            'msg'  => $e->getMessage(),
            'data' => $request = $request->url()
        ];
        return json($result, $statusCode);
    }
}

感觉源码作者,借鉴了很多.结合自己的实践
才疏学浅,欢迎交流指正

你可能感兴趣的:(统一验证层的封装和全局异常抛出)