I need an advice how to handle function with lots of different return’s better.
I have this simple log in function in my class:
public function login($email, $password){
$record = // Go to database and find what we need.
if($record){
// Check pass, $user_match = TRUE;
} else {
return 1; //No such user. Please register!
}
$active = (1 == $record['is_active']) ? TRUE : FALSE;
$verified = (1 == $record['is_verified']) ? TRUE : FALSE;
//User email and password matched:
if($user_match == true){
if($verified === true){
// Start session and insert to db table "online_users"
// Check that user was inserted to table: $confirm = $stmt->rowCount();
if($confirm !== 1){
return 2; //Unexpected technical error. Please try again in a moment.
}
return 0; //0 means that all clear, we good to go.
} else {
return 3; //not verified
}
} else {
return 4; // no match with email and pass, reject!
}
}
The problem is, that now all the time I need to check all return’s, something like that:
$log = $user->login($_POST['email'], $_POST['pass']);
if($log === 0) {
//Log in & edirect
} elseif ($log === 1) {
//No such user. Tell to register
} elseif($log === 2){
//technical error, try again
} elseif($log === 3){
//Not verified
} elseif($log === 4){
//wrong password
It’s really annoying right now, and imagine if I would need to check like 20 return’s? Is there any better way? How to do it more efficient and faster?
Thanks in advance.
You should rethink the purpose of this function and structure the return types accordingly. If the purpose is to log the user in, there can only be one answer: it either worked or it didn’t. So the primary return type of the function should be a boolean. How to differentiate between different causes for failure is a different topic.
Option 1: throw exceptions:
Not necessarily the most elegant option, since a failed login isn’t really an exceptional circumstance.
Option 2: save the error state in the login provider:
Whether this is good or not depends on how the class is used otherwise, you may not want to make it too stateful.
Option 3: separate the problem of login from what is the user’s state entirely:
Option 4: return a status object:
That’s essentially what you’re doing now, just without the magic numbers.