Php 如何组织RESTAPI参数的解析和验证?
我有一个RESTAPI,它通过查询字符串具有许多参数。我想知道是否有人知道设计模式,或者是否有一种很好的方法来组织所有参数(对象、函数、数组、json)。现在我正在解析和验证同一个函数中的所有参数,非常难看的代码 理想情况下,我希望有一些方法来处理类似于数据库ORM甚至配置文件/array/json的参数。然而,我一直试图想出一个解决这个问题的办法,但没有任何运气 如有任何见解,将不胜感激 我的想法示例:Php 如何组织RESTAPI参数的解析和验证?,php,api,rest,Php,Api,Rest,我有一个RESTAPI,它通过查询字符串具有许多参数。我想知道是否有人知道设计模式,或者是否有一种很好的方法来组织所有参数(对象、函数、数组、json)。现在我正在解析和验证同一个函数中的所有参数,非常难看的代码 理想情况下,我希望有一些方法来处理类似于数据库ORM甚至配置文件/array/json的参数。然而,我一直试图想出一个解决这个问题的办法,但没有任何运气 如有任何见解,将不胜感激 我的想法示例: <?php ... $parameters = [ // ?fields=
<?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
],
....
];
在我看来,您似乎在寻找验证库。我最喜欢的是Symfony的:。我知道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)),
));