在Silex / Symfony 2中验证没有模型的POST数据?

时间:2012-08-10 22:03:05

标签: rest symfony silex

我正在构建一个只提供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);

3 个答案:

答案 0 :(得分:13)

您可以使用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;
  }

答案 1 :(得分:3)

如果你想用Symfony2构建一个API(与silex类似),这里有一个很好的教程:http://williamdurand.fr/2012/08/02/rest-apis-with-symfony2-the-right-way/

在silex上验证已发送值的最佳方法仍然是使用validation& form组件(带模型)!他们是为了执行这个!阅读Hugo Hamon创建的完整幻灯片,用silex构建API! http://www.slideshare.net/hhamon/silex-meets-soap-rest(查看第42页进行验证)

不要在操作中逐个验证已发送的元素。

通过这样做,您将保持代码清洁和进化!

答案 2 :(得分:1)

在Symfony Book中对此进行了很好的解释:http://symfony.com/doc/master/book/forms.html#adding-validation

相关问题