dou426098 2014-11-22 19:12
浏览 23

cakephp分页和瘦控制器

i am developing with cakephp (2.4.7) and i have problems with organizing my controllers and models to use pagination.

So far i put the most logic into the models (thin controller, big model). There i returned the results to the controller where i set the variables to display it on the view.

But now i want to use pagination. This break my concept because i can not use pagination inside the models.

Whats the best solution to solve this problem? I do not want to reorganzie my whole structure, because i need pagination in a lot of different actions and models.

For example:

Controller Users, action friends

public function friends($userid = null, $slug = null) {
    $this->layout = 'userprofile';      
    $this->User->id = $userid;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid User'));
    }

    $this->set('friends', $this->User->getFriendsFrom($userid));
}

User Model, function getFriendsFrom($user_from).. i need this method in different actions.

public function getFriendsFrom($user_from) {

    $idToFind = $user_from;

    $data = $this->FriendFrom->find('all', 
        array(
            'conditions'=>array(
                'OR'=> array(
                    array('user_to'=> $idToFind),
                    array('user_from'=> $idToFind)
                ),
                'AND' => array(
                    'friendship_status' => 1
                )
            ),
            'contain' => array('UserFrom.Picture', 'UserTo.Picture')
        )
    );

    $friendslist = array();
    foreach ($data as $i) {
        if ($i['FriendFrom']['user_from'] == $idToFind){
            $friendslist[] = $i['UserTo'];
        }
        elseif ($i['FriendFrom']['user_to'] == $idToFind){
            $friendslist[] = $i['UserFrom'];
        }
    }

    return $friendslist;
}

Whats the best way to design this concept to use pagination?

Thanks

  • 写回答

1条回答 默认 最新

  • dongtanlin0765 2014-11-24 07:16
    关注

    in Controller Users use cakephp Paginator

    var $helpers = array('Paginator');
    

    Now you call the following method

    function index() {
        $result = array(
            'recursive' => -1,
            'conditions' => array(...),
            'contain' => array(...),
            'limit' => '2'
        );
        // you can write the above code in your model
        $this->paginate = $result; 
        $users = $this->paginate('User');
    
        // Re-arrage $users 
    
        $this->set(compact('users'));
    }
    

    If any problem, let me know.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等