我有一个通过查询字符串有许多参数的rest 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
],
....
];
答案 0 :(得分:2)
在我看来,您正在寻找验证库。我最喜欢的是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)),
));
$input
将是$_GET
或使用parse_str
等获得的内容。也可以使用其他格式定义验证规则,例如YAML。