symfony7之DTO递归验证的问题
use App\Validator as MainAssert;
use Symfony\Component\Validator\Constraints as Assert;
#[MainAssert\LiveSession]
class LiveSessionDto
{
/**
* @param ?FileMetadataDto $liveSessionReport
* @param ?LiveSessionDataDto[] $liveSessionData
*/
public function __construct(
protected readonly ?FileMetadataDto $liveSessionReport,
#[Assert\Valid]
protected readonly ?array $liveSessionData,
) {
}
public function getLiveSessionReport(): ?FileMetadataDto
{
return $this->liveSessionReport;
}
public function getLiveSessionData(): ?array
{
return $this->liveSessionData;
}
}
然后在LiveSessionDataDto下对title属性使用了NotBlank验证:
<?php
namespace App\Model\Dto\Input;
use Symfony\Component\Validator\Constraints as Assert;
class LiveSessionDataDto
{
public function __construct(
protected ?int $id,
#[Assert\NotBlank(message: 'This field is required.')]
protected string $title,
) {
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
}
要想让这个DTO中的 NotBlank 生效,需要给父级添加 #[Assert\Valid], 否则不生效.
总结: 在 Symfony 里,递归验证需要用 #[Assert\Valid] 标记在父 DTO 的属性上。
