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 に答える