复合
与其他约束相反,此约束不能单独使用。相反,它允许您通过扩展约束来创建自己的可重用约束集,表示在整个应用程序中一致使用的规则。
基本用法
假设您在不同的地方需要验证用户密码,您可以创建自己的命名集或需求,以便在任何地方一致地重用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// src/Validator/Constraints/PasswordRequirements.php
namespace App\Validator\Constraints;
use Symfony\Component\Validator\Constraints\Compound;
use Symfony\Component\Validator\Constraints as Assert;
#[\Attribute]
class PasswordRequirements extends Compound
{
protected function getConstraints(array $options): array
{
return [
new Assert\NotBlank(),
new Assert\Type('string'),
new Assert\Length(['min' => 12]),
new Assert\NotCompromisedPassword(),
new Assert\PasswordStrength(['minScore' => 4]),
];
}
}
如果您想在其他类中将其用作属性,请将 #[\Attribute]
添加到约束类。如果约束具有配置选项,请将它们定义为约束类上的公共属性。
您现在可以在任何需要的地方使用它
1 2 3 4 5 6 7 8 9 10
// src/Entity/User.php
namespace App\Entity\User;
use App\Validator\Constraints as Assert;
class User
{
#[Assert\PasswordRequirements]
public string $plainPassword;
}
验证组和负载可以通过构造函数传递
1 2 3 4 5 6 7 8 9 10 11 12 13
// src/Entity/User.php
namespace App\Entity\User;
use App\Validator\Constraints as Assert;
class User
{
#[Assert\PasswordRequirements(
groups: ['registration'],
payload: ['severity' => 'error'],
)]
public string $plainPassword;
}
7.2
Symfony 7.2 中引入了支持将验证组和负载传递给 Compound
类的构造函数。
这项工作,包括代码示例,根据 Creative Commons BY-SA 3.0 许可证获得许可。