So I wrote a flag feature for flagging comments, and I’m checking in my controller to see if the user has already flagged a particular comment. The problem is, I think this can be done in the Model.
The function is:
private function userAlreadyFlagged($userId, $commentId) {
$userAlreadyFlagged = $this->CommentsFlag->find('count', array(
'conditions' => array('CommentsFlag.comment_id' => $commentId, 'CommentsFlag.user_id' => $userId)
));
if ($userAlreadyFlagged > 0) {
return true;
} else {
return false;
}
}
Then I have another function also within the controller called flagComment
if (!$this->userAlreadyFlagged($userId, $commentId)) {
if ($this->CommentsFlag->save($this->request->data)) {
$message = array('response' => 'success');
}
} else {
$message = array('response' => 'alreadyFlagged');
}
My model for the CommentsFlag current links my users table to it:
var $name = 'CommentsFlag';
var $belongsTo = array(
'User' => array(
'className' => 'User'
)
);
So I’m wondering how I can start doing stuff like this in the model from now on, because I have a lot of code like this that would be better suited for the Model.
It is a good practice to have fat-models. What problem are you facing in moving the above functions to model?
Copy those functions into your model (CommentsFlag) and replace all
$this->CommentsFlag->find(...with$this->find(Consequently, to call above functions from your model, you can use:
$this->CommentsFlag->userAlreadyFlagged()if called from CommentsFlag’s controlleror
$this->User->CommentsFlag->userAlreadyFlagged()if called from User’s controller.