I have a model that I've created in Codeigniter to represent a vote. The purpose of the site that it's a part of is to allow users to vote on their preferred pronunciation for a given word.
The routine first checks to see if a user has registered a vote for the given pronunciation and if so, whether it was up or down. Just like the stackexchange network sites, you can only vote either up or down for a given entry and you can only vote once in either direction. Am I doing this wrong? Is there a simpler way to accomplish what I'm trying to do here (such as adding a method or two)? If there's anything else that you'd like to see that I haven't posted, let me know.
public function vote($pronun_id, $user_id, $direction) {
$data = array(
'pronun_id' => $pronun_id,
'user_id' => $user_id,
'direction' => $direction
);
$already_voted = $this->_vote_exists($pronun_id, $user_id);
if($already_voted == 'up') {
if($direction == 'up') {
return false;
}
else {
$this->db->where(array('user_id' => $user_id, 'pronun_id' => $pronun_id));
$this->db->update('vote', array('direction' => $direction));
return true;
}
}
elseif($already_voted == 'down') {
if($direction == 'down') {
return false;
}
else {
$this->db->where(array('user_id' => $user_id, 'pronun_id' => $pronun_id));
$this->db->update('vote', array('direction' => $direction));
return true;
}
}
else {
$this->db->insert('vote', $data);
return true;
}
}
private function _vote_exists($pronun_id, $user_id) {
$data = $data = array(
'pronun_id' => $pronun_id,
'user_id' => $user_id
);
$query = $this->db->get_where('vote', $data);
if($query->num_rows() > 0) {
$row = $query->row_array();
return $row['direction'];
}
else {
return false;
}
}
Update: Also, I'm very new to Codeigniter, so please feel free to be brutal about anything here. I'm not the best programmer and I also just don't know Codeigniter "style" yet, so either of those may be issues here.