0

我正在编写下面列出的以下代码,以根据各种值动态生成查询过滤器脚本。在某些情况下,这些值很少,但在某些情况下,它超出了限制,这看起来我的代码结构非常合理。

这是示例过滤器查询生成代码。

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";
    }

在代码中,它看起来像大量没有 if 条件,这使代码令人困惑并且看起来不太好,但它工作得很好。

有没有更好的方法来应对这种情况,以便生成复杂的过滤器查询,但使用更少的代码和更好的方法。

4

1 回答 1

1

这应该有效:

$filters = array();

if ($entity->iscomments != 2) {
    $filters[] = "v.iscomments=:iscomments";
}

if ($entity->galleryid > 0) {
    $filters[] = "v.galleryid=:galleryid";
}

...

$script .= ' '.implode(' AND ', $filters);
于 2013-08-04T18:00:16.613 回答