我在Symfony项目中有两个实体,它们扩展了一个公共抽象类,并且我使用XML配置格式为每个实体定义了一个Symfony验证配置。
由于这两个实体具有从抽象类继承的一组公共属性,因此我将每个实体的规则复制到它们各自的验证配置中。
这显然是不理想的,因为有人可能会更改其中一个的规则,而忽略更新另一个的规则。
是否有一种XML配置策略,我可以为抽象类定义验证配置,然后为继承抽象类验证的每个实体配置?
似乎这是可能的与Annotation配置,或PHP配置。但我不知道如何对XML或YAML做同样的事情。
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
,并且除了MyConcreteClass
验证器之外还需要加载AbstractClass
验证器——不需要额外的配置。