I have a web site, all coded in PHP (well and HTML, JavaScript, SQL, etc). I am currently making an iPhone App for this website, and to access the different SQL data I need, I am building a kind of API. Up until now, I only needed very simple data, so with one query, an if/else, I would have my data, and I'd just echo it in JSON. All very simple.
But I now wanted to make the API for the signing up part of the website. On the page I'd receive the data from the iPhone app (username, password, email, etc.) and I'd have to check if the username isn't used yet, if the passwords are valid and match, if the email is valid and not used yet, etc. If one of the conditions doesn't match, I obviously have to tell the app where it has gone wrong. And if they are all OK, then I sign up, and I tell the app I've done it.
But I'm not very familiar with the JSON/API concept, and I don't know what the right way do to it is. How do you deal with multiple responses in JSON, etc. The question may sound basic, but that's exactly where I am. I mean, I'd do something like this:
if ($_POST['pass'] == $_POST['pass_confirm']) {
if(!isValidPassword($_POST['pass'])){
echo '{"success":0,"error_message":"Password invalid"}';
}else{
The whole way. But that gives me a huge ass code, which could quite clearly be simplified, because the same elements are repeated time after time. But I can't get my head around it. So, how could I simplify the whole process of verifying the signing up and sending back the JSON data.
This is my suggestion. Only output your JSON a single time. Wrap the output in a function call such as function showOutput($success, $message) {}
. Set your conditionals up so that you're testing for error rather than for success, i.e.:
if($pass !== $pass_confirm) {
showOutput(false, 'Passwords don\'t match');
return;
}
// Here I know I'm still on a successful track
This is also known as guard clauses and will help keep you from implementing the arrow anti-pattern that you may already be suffering from, or could develop in the future should additional requirements be added. Contrast that with your current approach:
if($pass === $pass_confirm) {
if($someotherCondition) {
if($managerBobsCondition) {
// success!
}
}
}
That code could be refactored to look like this:
if($pass !== $pass_confirm) {
// error!
}
if(!$someotherCondition) {
// error!
}
if(!$managerBobsCondition) {
// error!
}
// success!
Which is a lot cleaner / easier to read. Adding additional requirements is also much more straightforward, because you don't have a complicated logic tree that you need to sort through to figure out where exactly you need to put the new else if
condition!