ThinkPHP的数据验证设计

人活在世上,无非是面对两大世界,身外的大千世界和自己的内心世界。

一般的验证方式

新建验证文件
tp5\application\api\validate\TestValidate.php

1
2
3
4
5
6
7
8
9
10
11
namespace app\api\validate;

use think\Validate;

class TestValidate extends Validate
{
protected $rule = [
'name' => 'require|max:10',
'email' => 'email'
];
}

控制器中调用验证

1
2
3
4
5
6
7
8
9
10
11
12
13
public function getBanner()
{
$data = [
'name' => 'yangzie',
'email' => 'yangzie@@.com'
];

$validate = new TestValidate();

$result = $validate->batch()->check($data); // true

var_dump($validate->getError());
}

控制器调用

这里需要验证传入的ID必须是一个正整数;
tp5\application\api\controller\v1\Products.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
use app\api\validate\IDMustBePositiveInt;

public function getAllInCategory($id)
{
(new IDMustBePositiveInt())->goCheck();

$res = Product::getProductsByCategoryID($id);

if ($res->isEmpty()) {
throw new ProductException();
}

return $res;
}

验证基类

这里包含了所有验证类需要调用的一些公共方法
tp5\application\api\validate\BaseValidate.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

namespace app\api\validate;

use app\lib\exception\ParameterException;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
public function goCheck()
{
$request = Request::instance();
$params = $request->param();

if (!$this->batch()->check($params)) {

$e = new ParameterException([
'msg' => is_array($this->error) ? implode(';', $this->error) : $this->error,
]);

throw $e;
}
return true;
}

protected function isPositiveInteger($value, $rule='', $data='', $field='')
{
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
return true;
}
return false;
}

protected function isNotEmpty($value, $rule='', $data='', $field='')
{
if (empty($value)) {
return $field . '不允许为空';
} else {
return true;
}
}

public function getDataByRule($arrays)
{
if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) {
// 不允许包含user_id或者uid,防止恶意覆盖user_id外键
throw new ParameterException([
'msg' => '参数中包含有非法的参数名user_id或者uid'
]);
}

$newArray = [];
foreach ($this->rule as $key => $value) {
$newArray[$key] = $arrays[$key];
}
return $newArray;
}

protected function isMobile($value)
{
$rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
$result = preg_match($rule, $value);
if ($result) {
return true;
} else {
return false;
}
}
}

ID 验证类

tp5\application\api\validate\IDMustBePositiveInt.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php

namespace app\api\validate;

class IDMustBePositiveInt extends BaseValidate
{
protected $rule = [
'id' => 'require|isPositiveInteger',
];

protected $message = [
'id' => 'ID必须是正整数'
];
}