简单的codeigniter重构问题 - 最佳实践

Dir*_*irk 0 refactoring codeigniter

我有一个关于重构PHP代码的快速问题.以下是三个功能.前两个看起来非常相似,只有一个if语句不同.第三个通过使用标志结合前两个.这是最好的做法吗?这里似乎可以使用一个标志,但如果我们将来需要添加更多标志呢?什么是最佳做法?

谢谢.

function check_contact_email($email) 
{ 
  $this->db->select('COUNT(login) AS count'); 
  $this->db->from('users'); 
  $this->db->where('email', $email); 
  $query = $this->db->get(); 
  $row = $query->row(); 
  return ($row->count > 0); 
} 

function check_contact_email_id($email) 
{ 
  $this->db->select('COUNT(login) AS count'); 
  $this->db->from('users'); 
  $this->db->where('email', $email); 
  $this->db->where('user_id !=', $_POST['user_id']); 
  $query = $this->db->get(); 
  $row = $query->row(); 
  return ($row->count > 0); 
} 

function check_contact_email($email, $id = FALSE) 
{ 
  $this->db->select('COUNT(login) AS count'); 
  $this->db->from('users'); 
  $this->db->where('email', $email); 
  if ($id) $this->db->where('user_id !=', $_POST['user_id']); 
  $query = $this->db->get(); 
  $row = $query->row(); 
  return ($row->count > 0);  
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*eon 5

首先,您可以通过使用一些鲜为人知(但记录在案)的ActiveRecord方法来减少这一切,如下所示:

function check_contact_email($email) 
{ 
  $this->db->where('email', $email); 
  return $this->db->count_all_results('users') > 0; 
} 

function check_contact_email_id($email) 
{ 
  $this->db->where('user_id !=', $_POST['user_id']); 
  return $this->check_content_email($email); 
} 

function check_contact_email($email, $id = FALSE) 
{ 
  if ($id) $this->db->where('user_id !=', $_POST['user_id']); 
  return $this->check_content_email($email); 
}
Run Code Online (Sandbox Code Playgroud)

您可以通过传递标志的数组来减少这种情况:

function check_contact_email($params) 
{ 
    if( is_array($params) )
    {
        $this->db->where($params);
    }

    else
    {
        $this->db->where('email', $params);
    } 

    return $this->db->count_all_results('users') > 0; 
}
Run Code Online (Sandbox Code Playgroud)

有了这个,你有一个可以以各种方式行动的功能:

$this->your_model->check_contact_email($email);

$this->your_model->check_contact_email(array(
    'email' => $email,
    'id !=' => $this->input->post('user_id')
));

$this->your_model->check_contact_email(array(
    'email' => $email,
    'id !=' => $this->input->post('user_id'),
    'otherfield' => $whatever
));
Run Code Online (Sandbox Code Playgroud)

将TINY数据库逻辑(!=)放入控制器中并不是完美的MVC,但将表单数据直接放入模型函数同样糟糕,因此请选择最灵活的方法.