I am currently adding a voting system to my website. Below is my voting class. I feel that it could be simplified and that there is repeated code regarding the functions, although to the best of my knowledge this is the simplest I can make it. I would love to hear other implementation ideas and systems that have been used.
<?php
class Vote{
var $db;
function __construct($db){
$this->db = $db;
}
function vote($user_id, $post_id, $type){
// check if vote already exists against user and post to prevent duplicates
if($this->userVoteExists($user_id, $post_id)){
// retreive vote
$vote = $this->getVote($user_id, $post_id);
// check if the requested vote is the same to prevent needlessly deleting and inserting
if($vote['type'] != $type){
if($vote){
// remove the vote if it exists
$this->removeVote($user_id, $post_id);
}
// add the vote
$this->addVote($user_id, $post_id, $type);
}
}
}
function userVoteExists($user_id, $post_id){
$query = $this->db->prepare("SELECT * FROM votes WHERE user_id = :user_id AND post_id = :post_id LIMIT 1");
$query->execute(array(':user_id' => $user_id, ':post_id' => $post_id));
return $query->rowCount();
}
function getVote($user_id, $post_id){
$query = $this->db->prepare("SELECT * FROM votes WHERE user_id = :user_id AND post_id = :post_id LIMIT 1");
$query->execute(array(':user_id' => $user_id, ':post_id' => $post_id));
return $query->fetch();
}
function removeVote($user_id, $post_id){
$query = $this->db->prepare("DELETE FROM votes WHERE user_id = :user_id AND post_id = :post_id");
$query->execute(array(':user_id' => $user_id, ':post_id' => $post_id));
}
function addVote($user_id, $post_id, $type){
$timestamp = time();
$query = $this->db->prepare("
INSERT INTO votes (
post_id,
user_id,
type,
timestamp
) VALUES (
:post_id,
:user_id,
:type,
:timestamp
)");
$query->execute(array(
':post_id' => $post_id,
':user_id' => $user_id,
':type' => $type,
':timestamp' => $timestamp
));
}
}
?>
function userVoteExists()
&function getVote()
? \$\endgroup\$