我想用symfony2构建一个文章配置器。在我的第一个实体中,存储了所有可能的文章配置。
实体PossibleArticle配置
名称:文章一
最小长度:250最大长度:500
最小宽度:250
最大宽度:500
我的第二个实体中的一个对象如下:
实体
配置粒子
名称:第一条
长度:300
宽度:400
是否有任何最佳实践可以基于PossibleArticleConfiguration中的最小和最大范围来验证ConfiguredArticle对象?
提前感谢
我会创建一个自定义约束。如果这两个实体没有与映射相关联,则可以注入对象管理器。如果您已经为实体映射了关联,回调也可能起作用。
http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
在ConfiguredArticle实体中,您可以使用以下方法
public function isLengthValid(ExecutionContextInterface $context) {
if ($this->getLength < $this->getArticleConfiguration()->getMinLength()) {
$context->addViolationAt('length', 'The length does not satisfy the minimum length', array(), null);
}
if ($this->getLength > $this->getArticleConfiguration()->getMaxLength()) {
$context->addViolationAt('length', 'The length does not satisfy the maximum length', array(), null);
}
}
public function isWidthValid(ExecutionContextInterface $context) {
if ($this->getWidth < $this->getArticleConfiguration()->getMinWidth()) {
$context->addViolationAt('width', 'The width does not satisfy the minimum width', array(), null);
}
if ($this->getWidth > $this->getArticleConfiguration()->getMaxWidth()) {
$context->addViolationAt('width', 'The width does not satisfy the maximum width', array(), null);
}
}
在本页上阅读有关如何使用回调方法进行验证的更多信息:http://symfony.com/doc/current/reference/constraints/Callback.html