TP3.2的简单数据验证类

浏览:5549 发布日期:2016/03/29 分类:功能实现
用于处理Model进入数据的验证
很多时候,我们在Model中处理数据的时候会一次传入很多参数,这时候可能需要对参数进行判断,是不是少参数了,参数的格式是否正确,如果每次都一大堆if判断的话会很麻烦,以前用过CI,它里面有对form表单提交的数据进行验证的类,然后按照我的习惯写了这个方法。

Validator.class.php<?php

/**
 * 数据验证类
 * 
 * @author Coeus <r.anerg@gmail.com>
 */

namespace Lib\Util;

class Validator {

    private $_vals;
    private $_rules;
    private $_errs;
    private $_error_code;

    public function set_rule($val, $rule, $err_code = -999) {
        $this->_vals[]  = $val;
        $this->_rules[] = $rule;
        $this->_errs[]  = $err_code;
        return $this;
    }

    public function ErrorCode() {
        return $this->_error_code;
    }

    private function reset() {
        $this->_vals       = array();
        $this->_rules      = array();
        $this->_errs       = array();
    }

    public function run() {
        foreach ($this->_rules as $index => $rule) {
            $_errs   = $this->_errs[$index];
            $errs    = explode('|', $_errs);
            $methods = explode('|', $rule);
            if (!in_array('required', $methods) && ($this->_vals[$index] === false || $this->_vals[$index] === '' || $this->_vals[$index] === null))
                continue;
            foreach ($methods as $k => $method) {
                if (preg_match('/(.*?)\[(.*)\]/', $rule, $match)) {
                    $method = 'rule_' . $match[1];
                    $param  = $match[2];
                    if (method_exists($this, $method) && $this->$method($index, $param) === false) {
                        $this->_error_code = isset($errs[$k]) ? $errs[$k] : -999;
                        $this->reset();
                        return false;
                    }
                } else {
                    $method = 'rule_' . $method;
                    if (method_exists($this, $method) && $this->$method($index) === false) {
                        $this->_error_code = isset($errs[$k]) ? $errs[$k] : -999;
                        $this->reset();
                        return false;
                    }
                }
            }
        }
        $this->reset();
        return true;
    }

    private function rule_trim($index) {
        $this->_vals[$index] = trim($this->_vals[$index]);
    }

    private function rule_required($index) {
        return $this->_vals[$index] !== '' && $this->_vals[$index] !== false && $this->_vals[$index] !== null ? true : false;
    }

    private function rule_regex_match($index, $regex) {
        return (bool) preg_match($regex, $this->_vals[$index]);
    }

    private function rule_matches($index, $match_val) {
        return (bool) $this->_vals[$index] === $match_val;
    }

    private function rule_integer($index) {
        return (bool) preg_match('/^[\-+]?[0-9]+$/', $this->_vals[$index]);
    }

    private function rule_mobile($index) {
        return (bool) preg_match('/^1[3|4|5|7|8]\d{9}$/', $this->_vals[$index]);
    }
    
    private function rule_min_len($index, $val) {
        return strlen($this->_vals[$index]) >= $val;
    }
    private function rule_max_len($index, $val) {
        return strlen($this->_vals[$index]) <= $val;
    }

}
一般来说,我不喜欢把其他东西放进ThinkPHP文件夹下,所以有一个Lib文件夹,在Application文件夹下。然后配置config.php文件,修改如下'AUTOLOAD_NAMESPACE'    => array('Lib' => APP_PATH . 'Lib'), //应用类库这样就可以正常加载了。

另外,验证的配置文件我是单独放的,所以我的function.php文件里多了一个函数/**
 * 加载扩展的配置参数
 * @param type $file_name
 * @param type $is_common
 */
function load_ext_config($file_name, $is_common = true) {
    $file_path = $is_common ? COMMON_PATH . 'Conf/' . $file_name . '.php' : MODULE_PATH . 'Conf/' . $file_name;
    if (is_file($file_path)) {
        $_config[$file_name] = load_config($file_path);
        C($_config);
    }
}
在Model中,具体使用示例如下:    public function __construct() {
        load_ext_config('Valid');
    }

    /**
     * 创建订单
     * @param type $params
     * @return boolean
     */
    public function create($params) {
        if ($this->_valid($params, __FUNCTION__) === false) {
            return false;
        }
        .............
    }
    /**
     * 字段格式及内容验证
     * @param type $params
     * @param type $method
     * @return boolean
     */
    private function _valid($params, $method) {
        $Rules     = C("VALID.ORDER");
        $Validator = new \Lib\Util\Validator();
        foreach ($Rules[$method] as $k => $v) {
            if ($Validator->set_rule($params[$k], $v['rule'], $v['err'])->run() === false) {
                $this->setErr($Validator->ErrorCode());
                return false;
            }
        }
        return true;
    }
数据验证的配置文件内容:<?php

return array(
    'ORDER' => array(
        'create'         => array(
            'order_time'     => array(
                'rule' => 'integer',
                'err'  => '-902001'
            ),
            'order_fee'      => array(
                'rule' => 'required|integer',
                'err'  => '-903002|-903001'
            ),
            'order_cost'     => array(
                'rule' => 'required|integer',
                'err'  => '-904002|-904001'
            ),
            'order_status'   => array(
                'rule' => 'integer',
                'err'  => '-905001'
            ),
            'order_channel'  => array(
                'rule' => 'required|integer',
                'err'  => '-906002|-906001'
            ),
            'order_discount' => array(
                'rule' => 'integer',
                'err'  => '-907001'
            ),
            'uid'            => array(
                'rule' => 'required|integer',
                'err'  => '-106002|-106001'
            ),
        ),
评论( 相关
后面还有条评论,点击查看>>