I have a method which creates an object of the User class, But If the user is not found I need to return something, but I am not sure WHAT:
function getUserById($id)
{
$sth = $this->db->prepare("SELECT id, username, password, salt, email, created, last_active FROM users WHERE id = ?");
$sth->execute(array($id));
$sth->setFetchMode(PDO::FETCH_OBJ);
if ($sth->rowCount() == 0) {
//return what?
}
$row = $sth->fetch();
$user = new User($row);
return $user;
}
And the method should be used something like this:
$user = $user_mapper->getUserById($id);
The question is how should I handle If the user is not found? Should I use a try catch block and then throw an exception in the rowCount == 0 if statement, or just return false and use a if statement when I set the $user variable to the object?
That is completely up to you and your error handling philosophy.
I’d decide this based on: Is this an exceptional event? Should this never ever happen?
If the answer is yes, throw an exception. If the answer is this may happen, I just need to handle this case,
return false.