我正在编写下面列出的代码,以根据各种值动态生成查询过滤器脚本。在某些情况下,这些值很少,但在某些情况下,它超出了限制,看起来我的代码结构非常复杂。
以下是示例过滤器查询生成代码。
if ($entity->iscomments != 2)
{
$script .= " v.iscomments=:iscomments";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isprivate != 3 || $entity->isexternal != 3 || $entity->datefilter > 0 || $entity->filter > 0 || $entity->mode > 0 || $entity->galleryid > 0)
$script .= " AND";
}
if ($entity->galleryid > 0)
{
$script .= " v.galleryid=:galleryid";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isprivate != 3 || $entity->isexternal != 3 || $entity->datefilter > 0 || $entity->mode > 0)
$script .= " AND";
}
if ($entity->isprivate != 3)
{
$script .= " v.isprivate=:isprivate";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isexternal != 3 || $entity->datefilter > 0 || $entity->mode > 0)
$script .= " AND";
}
if ($entity->mode > 0)
{
$script .= " v.mode=:mode";
if ($entity->term != "" || $entity->categoryid != 0 || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isexternal != 3 || $entity->datefilter > 0)
$script .= " AND";
}
if ($entity->categoryid != 0)
{
$script .= " v.categoryid=:categoryid";
if ($entity->term != "" || $entity->isfeatured != 3 || $entity->type != 2 || $entity->username != "" || $entity->month > 0 || $entity->isenabled != 2 || $entity->isapproved != 2 || $entity->isadult != 2 || $entity->isexternal != 3 || $entity->datefilter > 0)
$script .= " AND";
}
在代码中,它看起来像是条件的巨大数量,它使代码变得不合适而且看起来不太好但是效果很好。
有没有更好的方法来应对这种情况,以便生成复杂的过滤器查询,但使用更少的代码和更好的方式。
答案 0 :(得分:1)
这应该有效:
$filters = array();
if ($entity->iscomments != 2) {
$filters[] = "v.iscomments=:iscomments";
}
if ($entity->galleryid > 0) {
$filters[] = "v.galleryid=:galleryid";
}
...
$script .= ' '.implode(' AND ', $filters);