为扩展公共抽象类的对象继承Symfony Validation配置

时间:2016-10-27 23:16:42

标签: php validation symfony inheritance

我在Symfony项目中有两个实体扩展了一个公共抽象类,我使用XML配置格式为每个实体定义了一个Symfony Validation配置。

因为这两个实体具有从抽象类继承的公共属性集,所以我将每个实体的规则复制到它们各自的验证配置中。

这显然不理想,因为有人可能会更改一个规则而忽略更新另一个规则。

是否有XML配置的策略,我可以为抽象类定义验证配置,然后为每个继承抽象类验证的实体配置?

使用Annotation配置或PHP配置似乎可以实现这一点。但我不知道如何对XML或YAML做同样的事情。

1 个答案:

答案 0 :(得分:0)

Symfony将自动检查类的层次结构并加载为所涉及的每个类定义的任何验证器。

所以请使用以下PHP类:

<?php

abstract class AbstractClass {
    protected $inheritedProperty;
}

class MyConcreteClass extends AbstractClass {
    protected $myProperty;
}

MyConcreteClass的验证器只会描述它自己的属性(即$myProperty。)

<?xml version="1.0" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
                        http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    <class name="MyConcreteClass">
        <property name="myProperty">
            <constraint name="NotBlank" />
        </property>
    </property>
    </class>
</constraint-mapping>

AbstractClass的验证器只会描述它自己的属性(即$inheritedProperty。)

<?xml version="1.0" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping
                        http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    <class name="AbstractClass">
        <property name="inheritedProperty">
            <constraint name="NotBlank" />
        </property>
    </class>
</constraint-mapping>

验证MyConcreteClass对象时,Symfony会自动识别MyConcreteClass扩展AbstractClass,并且除了AbstractClass之外还需要加载MyConcreteClass验证程序验证器 - 无需额外配置。