i am developing with cakephp (2.4.7) and i want to know where is the best place (Controller, Model, etc) to write check functions to display different things (Buttons, Labels, ..) in the view.

For example, check if user has already liked a post (display "dislike" instead of "like") or check if users are friends and show "remove friend" instead of "add friend" button.

I know the question is very basic, but i don't know where i should place the code.


What i have: View

$hasLiked = $this->requestAction('/userlikes/hasliked/' . $postId); // returns true/ false
if ($hasLiked) {
   $this->Html->link('Dislike', array('controller' => 'userlikes', 'action' => 'dislike', $postId));
} else {
   $this->Html->link('Like', array('controller' => 'userlikes', 'action' => 'like', $postId));
}

UserlikesController

    public function hasliked($postId) {
    if (empty($this->request->params['requested'])) {
        throw new ForbiddenException();
    }       
    return $this->Userlikes->hasliked($postId, $this->Auth->user('id'));
}

Userlike Model

    public function hasliked($postId, $userId) {

    $result = $this->find('count', array('conditions' => array('post_id' => $postId, 'user_id' => $userId)));

    if ($result == 0) {
        return false;
    } else {
        return true;
    }

}

But i think my solution is very dirty, is there a better way? Thank you very much.

有帮助吗?

解决方案

i suggest to change your solution

Userlike Model

public function hasliked($postId, $userId) {

    return !empty($this->find('count', array('conditions' => array('post_id' => $postId, 'user_id' => $userId))));

}

UserlikesController

public function hasliked($postId) {
    if (empty($this->request->params['requested'])) {
        throw new ForbiddenException();
    }       
    $this->set('hasliked',$this->User->hasliked($postId,$this->Auth->user('id')));
}

In your view

<?php if($hasliked) :?>
<?php echo $this->Html->link('Dislike', array('controller' => 'userlikes', 'action' => 'dislike', $postId)); ?>
<?php else: ?>
<?php echo $this->Html->link('Like', array('controller' => 'userlikes', 'action' => 'like', $postId));; ?>
<?php endif;?>

其他提示

I think you miss one thing... Those features as Like, dislike, points etc are done by Ajax. So, make all your actions on simple and call them by Ajax. Like-

    public function like(){
    $this->autoRender = false; // If you wants to use this function just for ajax
     if($this->request->is('ajax')){
         // do something
         // capture all values send by Ajax and Call save function
     }else{
        return; // if not a ajax call, return
     }

   }

Its just an example---------- And one more thing, If you have thing to share same thing on View, better create element.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top