【问题标题】:Combine repeated property constraints in one Symfony custom validator在一个 Symfony 自定义验证器中组合重复的属性约束
【发布时间】:2014-04-09 14:39:11
【问题描述】:

我有一个应用程序,它具有不同的实体和密码属性。目前每个实体对密码属性都有一组重复的属性约束:

<?php
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
     // ...
     $metadata->addPropertyConstraint('password', new Length(...);
     $metadata->addPropertyConstraint('password', new NotBlank(...);
     $metadata->addPropertyConstraint('password', new Custom1(...);
     $metadata->addPropertyConstraint('password', new Custom2(...);
     // ...
}

我想要一个自定义验证器“PasswordValidator”,它可以“组合”上述所有不同的约束。在这种情况下,我只需要为每个密码属性添加一个属性约束。

像这样:

<?php
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
     // ...
     $metadata->addPropertyConstraint('password', new MyCustomPassword(...);
     // ...
}

有什么想法吗?

【问题讨论】:

    标签: php validation symfony


    【解决方案1】:

    您需要使用All Symfony2 内置约束:http://symfony.com/doc/current/reference/constraints/All.html

    基本上,在您的情况下应该是这样的:

    <?php
    use Symfony\Component\Validator\Constraints as Assert;
    
    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
         // ...
         $metadata->addPropertyConstraint(
            'password', 
            new Assert\All(
                new Assert\Length(...),
                new Assert\NotBlank(...),
                new Assert\Custom1(...),
                new Assert\Custom2(...)
            )
         );
    

    【讨论】:

    • 我想将这 4 个约束从实体中分离出来,这只是我的 sn-p 编码的另一种方式。
    • 那么,您可以实现自己的约束,该约束与给定的 All 约束非常相似,只是其成员将被硬编码。我个人认为它不会使您的代码更具可读性,而是相反。
    猜你喜欢
    • 1970-01-01
    • 2021-04-11
    • 2020-06-24
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 2015-01-11
    相关资源
    最近更新 更多