我想用 symfony2 构建一个文章配置器。在我的第一个实体中,存储了所有可能的文章配置。
实体可能的文章配置
名称:文章一
MinLength:250 MaxLength:500
MinWidth:250
MaxWidth:500
我的第二个实体中的一个对象如下所示:
实体
配置文章
名称:第一条
长度:300
宽度:400
是否有任何最佳实践可以根据可能的ArticleConfiguration 中的最小和最大范围来验证ConfiguredArticle 对象?
提前致谢
在 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
我会创建一个自定义约束。如果这两个实体没有与映射关联,您可以注入对象管理器。如果您已映射实体的关联,回调也可能会起作用。
http://symfony.com/doc/current/cookbook/validation/custom_constraint.html