liyuze / parameter-validator
参数和变量的数据类型和格式验证。
dev-master
2018-08-08 10:50 UTC
This package is not auto-updated.
Last update: 2024-11-04 15:51:24 UTC
README
PHP 语言的参数验证器和挂载器。
安装
//file:compose.json { "require": { "liyuze/parameter-validator": "dev-master" } }
compose update
或
compose require liyuze/parameter-validator dev-master
示例
参数集合对象初始化
-
单一指定
function func ($name, $age) { $Parameters = new liyuze\validator\Parameters\Parameters([ 'name' => $name, 'age'> $age, ]); }
-
数组指定
$Parameters = new liyuze\validator\Parameters\Parameters($_POST);
验证器
验证规则设置
-
设置验证规则
$Parameters->setRule([ 'name' => 'required|string|maxLength=15|minLength=5', 'age' => 'integer|max=120|min=1' ]);
-
参数和验证规则一同设置
$name = $_POST['name']; $age = $_POST['age']; $Parameters = new liyuze\validator\Parameters\Parameters(); $Parameters->config([ 'name' => [$name, ['required', 'string', 'maxLength' => 15, 'minLength' => 5]], 'age' => [$age, ['integer', 'max' => 120, 'min' => 1]] ]);
验证和验证消息
if ($Parameters->validate()) { //所有验证消息 $Parameters->getErrors(); }
验证消息
挂载器
新增自定义挂载器
/** * 由年龄获取生肖、出生年份 */ class AgeMounter extends liyuze\validator\Mounter\Mounter { public function registerKeys() { //挂载值的变量名 return ['year', 'zodiac'] } public function run() { //参数值 $value = $this->getParameter()->getValue(); //计算值 $year = 2018; $zodiac = 'dog'; //挂载值 return [ 'year' => $year, 'zodiac' => $zodiac ] } }
挂载器配置
$Parameters->addMounter('age', 'mounter\AgeMounter')
获取挂载值
//获取出生年份 $year = $Parameters->getMounteValue('age', 'year'); //获取属相 $zodiac = $Parameters->getParam('age')->getMounteValue('zodiac');