2011-02-26 2 views
2

이 방법은 검색 키워드와 구문 분석 된 mysql 쿼리를 검색하고 LIKE % 키워드 %를 포함하도록 where 식을 다시 작성합니다.이 방법을 별도의 방법으로 분해해야합니까?

그것은 잘 작동하지만, 나는 그것의 좋은 또는 나쁜 관행이 많은 루프와 방법을 가지고하면 잘 모릅니다 ...

private function build_where($query_array, $options) 
{ 
    //add WHERE starting point 
    $where = '';   

    if(!empty($query_array['WHERE'])) 
    { 
     //build where array 
     $where_array = $query_array['WHERE']; 

     //start the where 
     $where .= 'WHERE '; 

     //get columns array 
     $columns_array = $this->build_columns_array($query_array); 

     //if there is a search string   
     if(!empty($options['sSearch'])) 
     { 
      //check for enabled columns 
      $i = 0; 
      $columns_length = count($columns_array); 
      for($i; $i < intval($columns_length); $i++) 
      { 
       //create the options boolean array 
       $searchable_columns['bSearchable_'.$i] = $options['bSearchable_'.$i]; 
      } 

      //loop through searchable_columns for true values 
      foreach($searchable_columns as $searchable_column_key => $searchable_column_val) 
      { 
       if($searchable_column_val == true) 
       { 
        //get an integer from the searchable_column key 
        $column_id = preg_replace("/[^0-9]/", '', $searchable_column_key); 

        //lookup column name by index 
        foreach($columns_array as $columns_array_key => $columns_array_val) 
        { 
         //if the $columns_array_key matches the $column_id 
         if($columns_array_key == $column_id) 
         { 
          //loop to build where foreach base expression 
          $i = 0; 
          $where_length = count($where_array); 
          for($i; $i < intval($where_length); $i++) 
          { 
           //append the existing WHERE Expressions 
           $where .= $where_array[$i]['base_expr']; 
          }        

          //append the LIKE '%$options['sSearch'])%' 
          $where .= ' AND '.$columns_array_val." LIKE '%".$options['sSearch']."%' OR "; 
         } 
        } 
       } 
      } 
      //remove the last OR 
      $where = substr_replace($where, "", -3);          
     } 
     else 
     { 
      //loop to build where 
      $i = 0; 
      $where_length = count($where_array); 
      for($i; $i < intval($where_length); $i++) 
      { 
       $where .= $where_array[$i]['base_expr']; 
      } 
     }    
    } 

    //print_r($where_length); 
    return $where; 
} 

답변

2

깨는 방법은 주로 재사용에 관한 것이 아닙니다. 이렇게하면 코드를 읽고 테스트하고 유지 관리하기가 쉬워집니다. 명확한 메소드 이름은 인라인 주석을 대체 할 수도 있습니다. 이 메소드는 분리 할 수있는 두 개의 상위 레벨 작업을 수행합니다. 옵션이있는 where 절을 작성하고 옵션이없는 경우입니다. 나에게 또 다른 힌트는 옵션을 사용하여 where 절을 작성하는 논리가 자체 메서드를 보증 할만큼 충분히 육안으로 보인다는 것입니다.

private function build_where($query_array, $options) { 
    if(!empty($query_array['WHERE'])) { 
     $where_array = $query_array['WHERE']; 
     $columns_array = $this->build_columns_array($query_array); 
     if (empty($options['sSearch'])) { 
      return $this->build_where_with_options($where_array, $columns_array, $options); 
     } 
     else { 
      return $this->build_where_without_options($where_array, $columns_array); 
     } 
    } 
    else { 
     return ''; 
    } 
} 

지금 당신은 신속하게 각 형태의 결과를 생성하는 데 필요한 입력과 함께 세 가지 형태의 조항이 걸릴 수 있습니다 어디에와 있다는 것을 볼 수 build_where()를 스캔 할 수 있습니다.

여기에 약간의 개선은 당신이 당신의 코드를 통해 할 수 있습니다

  • count()는 정수를 반환하고 for 루프에서 intval() 호출을 필요로하지 않는다. 비록 당신이 그것들을 버려 두었다면, 루프 밖에서 호출을 적용하는 것이 더 좋을 것입니다. 그래서 매번 동일한 값을 산출하기 때문에 한 번만 수행됩니다.
  • if($searchable_column_val == true)은 둘 모두가 $searchable_column_val을 부울 값으로 캐스팅하고 후자가 부울 부울 값이 true 일 때 통과하므로 후자는 if($searchable_column_val)과 같습니다.
  • $where = substr_replace($where, "", -3)$where = substr($where, 0, -3)으로 바꿀 수 있으며 약간 더 명확합니다.
  • 특정 키를 찾는 배열을 반복하는 대신 PHP의 배열을 활용할 수 있습니다. 간단히 그 키로 값을 가져 오는 것입니다. 마지막 하나

,이 코드

foreach($columns_array as $columns_array_key => $columns_array_val) 
{ 
    //if the $columns_array_key matches the $column_id 
    if($columns_array_key == $column_id) 
    { ... } 
} 

$columns_array_val = $columns_array[$column_id]; 
... 
+0

굉장한 피드백 맨! 고맙습니다! – Peter

1

개인 취향 정말. 일부 프로그래머는 이것을 여러 기능으로 쪼개 버릴 것입니다. 개인적으로, 나는 그것이 당신이 그것을 가지고있는 것처럼 멋지다고 생각한다. 내가 재사용 할 수 있다고 생각되는 것을 보았다면, 그것을 포함 할 수있는 별도의 파일로 리팩터링했다.

제 생각에는 일부 프로그래머는 재사용 할 항목이 있기도 전에 "재사용 가능"하게 만들기에는 너무 빠릅니다.

+0

으로 대체 될 수는 응답 주셔서 감사합니다. 블록 전체를 제외하고는 해당 블록에서 재사용 할 수있는 것이 없습니다. – Peter

5

켄트 벡 (Kent Beck)이나 마틴 파울러 (Martin Fowler)에 대한 생각의 학교는이 큰 방법을 여러 가지 작은 방법으로 리팩토링하도록 조언합니다. 필자의 견해로는 리팩터링의 주된 이유가 될 것이다.

+0

답변과 설명에 감사드립니다. – Peter

관련 문제