doupingdiao3546 2015-04-09 21:28
浏览 52
已采纳

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?

  • 写回答

1条回答 默认 最新

  • douzi1350 2015-04-09 23:27
    关注

    PHP MVC - Is my controller too fat?

    Yeah, especially because it contains business logic, therefore no separation of concerns. And the reason is because you don't implement a model correctly. A model consists of data mappers and domain logic handlers. And things that bring data mappers and domain objects are called Services

    A model is not a class. Calling model a class is like calling class MyLiskovSubstitionClass {}. That's a concept of data asbtraction. Model consists of services.

    To implement it correctly, you'd start from writing a mapper:

    class UserMapper
    {
      public function getUsers()
      {
        $data = $this->_db->select("SELECT * FROM ".PREFIX."users" . $this->_sort);
        return $data;
      }
      // ... The rest what abstracts table access
    }
    

    And then you'd write a service, which is called UserManager

    final class UserManager
    {
          private $userMapper;
    
          public function __construct($userMapper)
          {
              $this->userMapper = $userMapper;
          }
    
          public function search(array $input)
          {
               $data = array();
    
               if (!isset($input["search"])) {
    
                 $data['Records'] = $this->userMapper->getUsers();
                 $data['Result'] = "OK";
                 $data['TotalRecordCount'] = $this->userMapper->countUsers();
    
                 // Do the rest
               }
    
               return $data;
          }
    }
    

    And finally :

    public function ajaxUsers()
    {
        if ($_GET["action"] == "listUsers") { 
          $result = $this->userManager->search($_POST);
          die(jscon_encode($result));
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)