构建一个通用的php验证的函数
每次处理web应用时特别是写入数据库时,进行数据验证是必须要进行的步骤而且繁琐 每次都要调用很多次,今天
闲着没有事情写个通用的函数 ,以后再要验证什么函数,加入自己的函数就可以了 :
<?php /** * php 数据过滤扩展 * * 需求:对提交的数据进行过滤要能够通用 * * 1:需要传递的参数是否存在 * 2:需要传递的参数是否合法 * 字段名称 过滤条件 提示信息 * * */ class DataFilter extends Exception{ public function __construct(){ } /** * 函数标准说明 * 函数名:filter * 功能说明:全面的过滤功能 可随意的添加自己的函数 * 参数说明:array('字段','使用的验证格式','对应的提示信息') * 返回值: json_decode(array('status'=flase,'message'='','fileds')) * 备注说明: * * 验证格式:array( * * array('md'='is_int','field'=>'name','message'=>'错误') * ) * * * * 要有严格的一一对应关系 * * 作者:刘纪君 * @copyright ch.gongchang.com * @time:2013-1-16 * email:liujijun@gongchang.com */ public function filter($param = array(),$data = array()) { //分析传递的数据 foreach ($param as $key=>$value){ //映射对象中的一个方法 $function = new ReflectionMethod($this, $value['md']); if (isset($value['arg'])){ $arr = $value['arg']; $arr[] =$data[$value['field']]; $status = $function->invokeArgs($this,$arr); }else{ $status = $function->invoke($this,$data[$value['field']]); } if (!$status){ throw new Exception($value['message']); break;//退出验证 } } } //验证是否是整数 public function is_int($input){ return false; } /**
加入自己的函数参数格式 注意参数的顺序
*/
} //反射 数组 $argArr = array( array('md'=>'is_int','field'=>'name','message'=>'错误'), array('md'=>'is_int','field'=>'name','message'=>'错误') ); $data['name'] = "ww"; $filter = new DataFilter(); try { $filter->filter($argArr,$data); }catch(Exception $e){ echo $e->getMessage(); }