继承扩展通用抽象类的对象的Symfony验证配置

考特尼·迈尔斯(Courtney Miles)

我在Symfony项目中有两个实体,它们扩展了一个通用的抽象类,并且我已经使用XML配置格式为每个实体定义了一个Symfony Validation配置。

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

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

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

似乎可以通过Annotation配置或PHP配置来实现。但是我看不到如何对XML或YAML进行同样的处理。

考特尼·迈尔斯(Courtney Miles)

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以及AbstractClassMyConcreteClass验证器外还需要加载验证器的功能-无需其他配置。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章