I am learning OOP and have written a class for Likes. There is a load, add, delete method and I think this code can be improved since there is a lot of duplication. Please let me know how I can improve on this code and secure this code:
fileA.php:
include_once dirname(__FILE__) . "/like.class.php";
$like = new Like($db);
if (isset($_POST['add'])):
$like->addLikes();
elseif (isset($_POST['delete'])):
$like->unLikes();
else:
$like->loadLikes();
endif;
like.class.php
public function loadLikes() {
$sql = //sql query
try
{
$imageid = $_POST['imageid'];
$imageid = htmlentities($imageid, ENT_QUOTES);
$author = $_POST['author'];
$author = htmlentities($author, ENT_QUOTES);
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
$count = $this->countLikes($imageid);
if ($query->rowCount() > 0) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($row['like'] == '1') {
$like = (array('like' => true));
$response = json_encode(array_merge($count, $like));
echo $response;
return TRUE;
}
elseif ($row['like'] == '2') {
$like = (array('unlike' => true));
$response = json_encode(array_merge($count, $like));
echo $response;
return TRUE;
}
else {
$error = "Invalid";
$response = json_encode(array('like' => false, 'text' => $error));
echo $response;
return FALSE;
}
}
}
else {
$like = (array('unlike' => true));
$response = json_encode(array_merge($count, $like));
echo $response;
return FALSE;
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
public function addLikes() {
$sql = //sql query
try
{
$imageid = $_POST['imageid'];
$imageid = htmlentities($imageid, ENT_QUOTES);
$author = $_POST['author'];
$author = htmlentities($author, ENT_QUOTES);
$query = $this->_db->prepare($sql);
$params = array(':imageid' => $imageid, ':author' => $author);
$query->execute($params);
if ($query->rowCount() > 0) {
//update like
$this->updLikes();
}
else {
//insert like
$this->insertLikes();
}
}
catch(PDOException $ex)
{
echo json_encode(array('like' => false, 'text' => $ex));
return FALSE;
}
}
I have only posted two methods because the other methods in the class all follow the same pattern. Is there anyway I can code this more efficiently reducing duplication? Any other pointers would be appreciated.
array
s in()
.$like = array('unlike' => true);
is easier to read and type. You should also stick to a standard when writing your syntax, usingTRUE
andtrue
looks sloppy. \$\endgroup\$ – PiZzL3 May 28 '11 at 18:04