gpt4 book ai didi

rest - 在Silex/Symfony 2中没有模型的情况下验证POST数据?

转载 作者:行者123 更新时间:2023-12-04 13:17:08 27 4
gpt4 key购买 nike

我正在构建一个仅提供json/xml数据的RESTful应用程序,我选择了Silex,因为我已经知道(一点)Symfony 2,并且因为体积小,我不需要Twig等。

没有模型,只有使用Doctrine dbal和序列化程序的普通SQL查询。无论如何,我应该验证POST/PUT请求。不使用表单组件和模型怎么办?

我的意思是POST数据是一个数组。我可以验证它(添加约束)吗?如何验证?

编辑:好的,现在我已经找到了一个有趣的库,即respect/validation。如果需要,它还会使用SF约束。我最终得到了这样的内容(早期代码:P),如果没有更好的方法,我将使用它:

$v = $app['validation.respect'];

$userConstraints = array(
'last' => $v::noWhitespace()->length(null, 255),
'email' => $v::email()->length(null, 255),
'mobile' => $v::regex('/^\+\d+$/'),
'birthday' => $v::date('d-m-Y')->max(date('d-m-Y')),
);

// Generic function for request keys intersection
$converter = function(array $input, array $allowed)
{
return array_intersect_key($input, array_flip($allowed));
};

// Convert POST params into an assoc. array where keys are only those allowed
$userConverter = function($fields, Request $request) use($converter) {

$allowed = array('last', 'email', 'mobile', 'birthday');

return $converter($request->request->all(), $allowed);
};

// Controller
$app->match('/user', function(Application $app, array $fields)
use($userConstraints) {

$results = array();

foreach($fields as $key => $value)
$results[] = $userConstraints[$key]->validate($value);

})->convert('fields', $userConverter);

最佳答案

好吧,您可以使用Symfony2 Validator组件来验证数组,例如

//namespace declaration    
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\NotBlank;
//....

//validation snippet

$constraint = new Collection(array(
'email' => new Email(),
'last' => new NotBlank(),
'birthday' => new Date(),
));

$violationList = $this->get('validator')->validateValue($request->request->all(), $constraint);

$errors = array();
foreach ($violationList as $violation){
$field = preg_replace('/\[|\]/', "", $violation->getPropertyPath());
$error = $violation->getMessage();
$errors[$field] = $error;
}

关于rest - 在Silex/Symfony 2中没有模型的情况下验证POST数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909853/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com