如何在cakePHP 1.2中简化查询代码

时间:2013-02-11 15:34:17

标签: php cakephp optimization cakephp-1.2

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

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语句)。

1 个答案:

答案 0 :(得分:-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。这使得将来修改代码更容易,并防止编码错误。