Hev*_*web 3 api validation rest symfony4
我将为我的项目编写 REST API。我正在使用 symfony 4。我看到了几个例子,但没有一个适合我。
所以,我想我需要编写验证器,它对所有可能的字段都有一组约束。我只是不知道什么是最好的呈现方式。你见过类似的东西吗?
PS 在写这篇文章之前,我使用了 stackoverflow 搜索。我没有找到有用的答案。
看看你的例子 ( example.com/api/categories?limit=20&offset=300&filter=something) 我猜你的动作看起来像这样:
public function getCategories(?int $limit, ?int $offset, ?string $filter)
{
//...
}
Run Code Online (Sandbox Code Playgroud)
您可以将约束定义为一个数组(然后将其抽象为自己的类),并将其作为第二个参数传递给验证器。
$constraint = new Assert\Collection([
'limit' => [
new Assert\Range(['min' => 0, 'max' => 999]),
new Assert\DivisibleBy(0.5)
],
'offset' => new Assert\Range(['min' => 0, 'max' => 999]),
'filter' => new Assert\Regex("/^\w+/")
]);
$validationResult = $this->validator->validate(
['limit' => $limit, 'offset' => $offset, 'filter' => $filter],
$constraint
);
Run Code Online (Sandbox Code Playgroud)
文档链接。
对于要验证的每个参数,将约束作为第二个参数传递给验证器。
$offsetValidationResult = $this->validator->validate(
$offset,
new Assert\Range(['min' => 0, 'max' => 999])
);
//...
Run Code Online (Sandbox Code Playgroud)
文档链接。
创建一个包含 3 个字段的类。
class FilterParameters
{
public function __construct($limit, $offset, $filter)
{
$this->limit = $limit;
$this->offset = $offset;
$this->filter = $filter;
}
// No getters/setters for brevity
/**
* @Assert\DivisibleBy(0.25)
*/
public $limit;
/**
* @Assert\Range(min = 0, max = 999)
*/
public $offset;
/**
* @Assert\Regex("/^\w+/")
*/
public $filter;
}
Run Code Online (Sandbox Code Playgroud)
实例化并验证它。
$validationResult = $this->validator->validate(
new FilterParameters($limit, $offset, $filter)
);
Run Code Online (Sandbox Code Playgroud)
文档链接。
| 归档时间: |
|
| 查看次数: |
7021 次 |
| 最近记录: |