我有一个休息api,通过查询字符串有很多参数.我想知道是否有人知道设计模式或有一个很好的方式来组织所有参数(对象,函数,数组,json).现在我正在解析和验证我在同一个函数中的所有参数,非常难看的代码.
理想情况下,我想要一些方法来处理类似于数据库ORM甚至配置文件/数组/ json的参数.但是,我试图想出一个没有任何运气的解决方案.
任何见解将不胜感激!
我的想法的例子:
<?php
...
$parameters = [
// ?fields=id,name
'fields' => [
'default' => ['id', 'name'],
'valid' => ['id', 'name', 'date],
'type' => 'csv', // list of values (id & name)
'required' => ['id'],
'replace' => ['title' => 'name'], // if the database & api names don't match
'relation' => null, // related database table
],
// ?list=true
'list' => [
'default' => ['false'],
'valid' => ['true', 'false'],
'type' => 'boolean' // single value (true or false)
'required' => [],
'replace' => [], // if the database & api names don't match
'relation' => 'category', // related database table
],
....
];
Run Code Online (Sandbox Code Playgroud)
在我看来,您正在寻找一个验证库。我最喜欢的是 Symfony 的: https: //github.com/symfony/validator。我知道 Zend Framework 2 也有一个验证组件。我个人没有使用过它,但我希望它也非常好。
symfony/validator 自述文件中的示例:
<?php
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;
$validator = Validation::createValidator();
$constraint = new Assert\Collection(array(
'name' => new Assert\Collection(array(
'first_name' => new Assert\Length(array('min' => 101)),
'last_name' => new Assert\Length(array('min' => 1)),
)),
'email' => new Assert\Email(),
'simple' => new Assert\Length(array('min' => 102)),
'gender' => new Assert\Choice(array(3, 4)),
'file' => new Assert\File(),
'password' => new Assert\Length(array('min' => 60)),
));
Run Code Online (Sandbox Code Playgroud)
$input也可以用$_GET其他parse_str格式定义验证规则,例如 YAML。