谈表单验证案例之ThinkPHP3.2使用ThinkPHP5.0+的Validate类

来源:互联网 发布:java开发师就业方向 编辑:程序博客网 时间:2024/05/20 11:19

对表单进行验证是非常繁琐,重复,但有不得不做的事情,自从用了laravel的验证类后,瞬间觉得脑洞打开,以前在javascript的有实现相关功能的函数,但没完整整理出封装出类的思路,下面由几个案例入手,最后在整理下该类实现的思路,tp5.0中的validate类有借鉴laravel的意思,下面的例子为在tp3.2中加载使用tp5.0中的validate类:

下载ThinkPHP5.0+,找到

thinkphp\library\think\Validate.php

复制到

framework\ThinkPHP\Library\Think

并且重命名:

Validate.php -> Validate.class.php

然后在框架 functions.php 文件里,添加大V方法。
functions.php 路径:

framework\ThinkPHP\Common
/** * 实例化验证类 格式:[模块名/]验证器名 * @param string $name         资源地址 * @param string $layer        验证层名称 * @param string $common       公共模块名 * @return Object|false * @throws Exception * * @author chengbin */function V($name = '', $layer = 'Validate', $common = 'Common'){    if (empty($name)) {        return new Think\Validate;    }    static $_validate  =   array();    $guid = $name . $layer;    if (isset($_validate[$guid])) {        return $_validate[$guid];    }    $class = parse_res_name( $name, $layer );    if (class_exists($class)) {        $validate = new $class;    } else {        if(!C('APP_USE_NAMESPACE')){            import('Common/'.$layer.'/'.$class);        }else{            $class      =   '\\Common\\'.$layer.'\\'.$name.$layer;        }        if (class_exists($class)) {            $validate = new $class;        } else {            throw new Exception('Validate Class Not Exists:' . $class);        }    }    $_validate[$guid] = $validate;    return $validate;}

调用实例:

$allInvestRecordValidate = V('AllInvestRecord');if( !$allInvestRecordValidate->scene('ret')->check( $request ) ) {    throw new \Exception( $allInvestRecordValidate->getError() );}

AllInvestRecord路径:

common\Common\Validate\AllInvestRecordValidate.class.php

AllInvestRecordValidate类:

<?phpnamespace Common\Validate;class AllInvestRecordValidate extends \Think\Validate{    protected $rule =   [        'loan_id' => 'require',    ];    protected $message  =   [        'loan_id.require' => '缺少参数 loan_id'    ];    protected $scene = [        //流标场景        'ret' => ['loan_id'],    ];}

验证类使用方法,可以参照ThinkPHP5.0+的Validate类文档:
http://www.kancloud.cn/manual/thinkphp5/129352