0
点赞
收藏
分享

微信扫一扫

REST API开发技巧集锦(5):参数错误校验(AOP)

AOP:Aspect Oriented Programming的缩写,意为:​​面向切面编程​​

实际开发中,需要校验很多参数,比如id为正整数,num必须为数字,tel必须为11位长度,emai必须为邮箱类型;

传统校验:依次判断 is_int($id) is_numeric($num) 等等

AOP思想:将这些参数校验看作是共同的一道工序,无论是哪个参数,只要是参数,就必须过参数校验这一道工序,因此可以将参数校验这一工序抽象出来,以后只要碰到参数,都会通过这个抽象层面去处理;

类似去电影院看电影:无论你是在网上买的,还是线下买的,无论是买的复联4,还是流浪地球,都会经过电影剪票口统一检票后才能进入影院看电影。

1、ParameterException.php

class ParameterException extends BaseException
{
//默认错误
public $code = 400;//http status code
public $msg = '参数错误';
public $errorCode = 10000;
}

2、BaseException.php

class BaseException extends Exception
{

public $code = 400;//http status code
public $msg = '错误';
public $errorCode = 10000;

public function __construct($params = [])
{
if (!is_array($params)){
return;
}

if (array_key_exists('code',$params)){
$this->code = $params['code'];
}

if (array_key_exists('msg',$params)){
$this->msg = $params['msg'];
}

if (array_key_exists('errorCode',$params)){
$this->errorCode = $params['errorCode'];
}

}
}

3、BaseValidate.php

class BaseValidate extends Validate
{

public function goCheck()
{
//get the params
$request = Request::instance();
$params = $request->param();

$request = $this->check($params); //若传入的参数未通过验证,则抛出异常错误
if (!$request){
$e = new ParameterException([
'msg' => $this->error,
// 'code' => 400 //可选参数
]);
throw $e;

}else{
return true;
}
}

}

4、控制器使用

(new IDMustBePositiveInt())->batch()->goCheck(); //验证参数

附:IDMustBePositiveInt验证

class IDMustBePositiveInt extends BaseValidate

{

protected $rule = [
'id' => 'require|isPositiveInteger',
// 'num' => 'in:1,2,3'
];

protected function isPositiveInteger($value, $rule='', $data='', $field=''){
if (is_numeric($value) && is_int($value + 0) && ($value + 0 > 0)){
return true;
}else{
return $field.'必须是正整数';
}

}

}

 

举报

相关推荐

0 条评论