複合
與其他約束條件相反,此約束條件不能單獨使用。相反地,它允許您透過擴展約束條件來建立自己的一組可重複使用的約束條件,代表在您的應用程式中一致使用的規則。
適用於 | 類別 或 屬性或方法 |
類別 | 複合 |
Validator | CompoundValidator |
基本用法
假設您在不同的地方需要驗證使用者密碼,您可以建立自己的命名集合或需求,以便在各處一致地重複使用
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 授權條款授權。