1

有人可以给我一些关于 Symfony2 如何使用 ORM 元数据自动构建验证规则的启示吗?我正在使用 Symfony2.1。

例如,如果我们有一个Foo具有必需属性的实体name,我们有以下 Doctrine 元数据(作为注释):

@ORM\Column(name="name", type="string", length=255, nullable=false)

但是,如果我们希望在服务器端对其进行验证,我们必须重复这些nullable信息:Assert

@Assert\NotBlank()

另一方面,如果我们有一个number带有integer类型的属性,它会自动用作验证规则,而无需使用任何@Assert注释。

@ORM\Column(name="number", type="integer", nullable=true)
//@Assert\Type(type="integer") is no needed
4

1 回答 1

3

Basically, you have two different layers:

The peristence layer adds validation rules to the database using metadata. In Doctrine2, you can use annotations, but with Propel you describe your database using XML. It's mainly used to define SQL statements (basically nullable=false is transformed in SQL NOT NULL).

The validation layer is used to validate your data at the application level. Doctrine2 metadata are used to construct your database while the Validation layer is used to validate data (from your users for example) before to insert them in the database.

You can add more constraints at the application level using the Validator component like business validation rules. And, you should not rely on the database to validate data.

As you have two different layers with two different concerns, you can't mix them.

于 2012-08-23T14:52:23.250 回答