PHP MVC - 我的控制器太胖吗?

I think I put too much code in my controller that was supposed to go in the model.

This is a part of my controller, I'm not gonna paste everything since there is a lot of code.

  public function ajaxUsers() {
    if($_GET["action"] == "listUsers") {

        if(!isset($_POST["search"])) {
            $this->_data['Records'] = $this->_model->getUsers();
            $this->_data['Result'] = "OK";
            $this->_data['TotalRecordCount'] = $this->_model->countUsers();
        }
        else {
            foreach($_POST['fields'][0] as $key => $post) {
                if ($post != "" && $key != "reg_date") {
                    $searchTerms = explode(' ', $post);
                    foreach ($searchTerms as $term) {
                        $term = trim($term);
                        if (!empty($term)) {
                            $like[] = $key." LIKE '%".trim($term, '\'')."%'";
                        }
                    }

                }
                else if ($post != "" && $key == "reg_date") {
                    foreach ($post[0] as $key2 => $date) {
                        $datetofrom = strtotime($date);
                        $datetofrom = date('Y-m-d', $datetofrom);
                        if ($date != "" && $key2 == "datefrom") {
                            $like[] = "DATE_FORMAT(".$key.", '%Y-%m-%d') >= '".$datetofrom."'";

                        }
                        if ($date != "" && $key2 == "dateto") {
                            $like[] = "DATE_FORMAT(".$key.", '%Y-%m-%d') <= '".$datetofrom."'";
                        }
                    }
                }
            }

            ($like) ? $where_clause = "WHERE ". implode(' AND ', $like) : $where_clause = "";   
            $this->_data['Records'] = $this->_model->filterUsers($where_clause);
            $this->_data['Result'] = "OK";
            $this->_data['TotalRecordCount'] = $this->_model->countfilterUsers($where_clause);
        }
        echo json_encode ($this->_data);
    }
}

And my model is mostly database queries:

  public function getUsers() {
    $data = $this->_db->select("SELECT * FROM ".PREFIX."users" . $this->_sort);
    return $data;
}

public function countUsers() {
    $data = $this->_db->select("SELECT count(*) as id FROM ".PREFIX."users");
    return $data[0]->id;
}

public function filterUsers($like_clause) {
    $data = $this->_db->select("SELECT * FROM ".PREFIX."users " .$like_clause. $this->_sort); 
    return $data;
}
public function countFilterUsers($like_clause) {
    $data = $this->_db->select("SELECT count(*) as id FROM ".PREFIX."users ".$like_clause);
    return $data[0]->id;
} 

Should I moved the foreach loops in the model?

查看全部
doupingdiao3546
doupingdiao3546
2015/04/09 21:28
  • php
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复