0

我的控制器中有这部分代码:

if ((!empty($params))&&(isset($params['autore'])||isset($params['titolo'])||isset($params['editore'])||isset($params['anno']))) {
        $a = $params['autore'];
    if (strpos($a,' ')||strpos($a,',')) {
        $autore_diviso = explode(" ", $a);
        $this->set('autore_diviso', $autore_diviso);
    }
    $t = $params['titolo'];
    $e = $params['editore'];
    $an = $params['anno'];
    $an2 = $params['anno2'];

    if ($an==''&&$an2=='')
            $conditions = array('AND' => array('autori LIKE' => "%$a%",
                'editore LIKE' => "%$e%",'titolo LIKE' => "%$t%"));                     
        else    
        {
            if ($an=='')
                      $conditions = array(array('AND' => array('autori LIKE' => "%$a%",
                      'editore LIKE' => "%$e%",'titolo LIKE' => "%$t%")),
                    'AND' => array('anno <=' => "$an2"));
            if ($an2=='')
                $conditions = array(array('AND' => array('autori LIKE' => "%$a%", 'editore LIKE' => "%$e%",'titolo LIKE' => "%$t%")),                   'AND' => array('anno >=' => "$an"));
            else
                $conditions = array('AND' => array(
                            'autori LIKE' => "%$a%", 'editore LIKE' => "%$e%",
                            'titolo LIKE' => "%$t%"),
                            'OR' => array('anno BETWEEN ? AND ?' => array($an,$an2)));
        }
        $u = $this->paginate('CdBiblio',$conditions);
            $this->set('query', $u);
    }

(其中“anno”的意思是“年份”——titolo = 'title' 和 editore = 'publisher')。

如何简化此代码?

另外,我需要介绍用户搜索 2 个作者的可能性(所以我会添加更多 if ... else 语句)。

4

1 回答 1

-2

看来您在所有条件下都有相同的子查询。

您可以通过这种方式使用串联来保存代码:

//common subquery
$conditions = array('AND' => array(
                        'autori LIKE' => "%$a%", 'editore LIKE' => "%$e%",
                        'titolo LIKE' => "%$t%"));

//for example...  
if(...){
    $conditions+=array('AND' => array('anno <=' => "$an2"));
}else{
    $conditions+=array('OR' => array('anno BETWEEN ? AND ?' => array($an,$an2)));
}

$u = $this->paginate('CdBiblio',$conditions);

您还可以更改比较:

if ($an==''&&$an2=='')

为了

if (!$an && !$an2)

哦,还有……我会用真实的词来表示变量。总是更好地理解什么是什么,而不是创建没有意义的变量,例如$a. 这使得将来修改代码和防止编码错误变得更容易。

于 2013-02-11T15:42:45.083 回答