Link to home
Start Free TrialLog in
Avatar of DrDamnit
DrDamnitFlag for United States of America

asked on

How to make this code clean / readable?

The code below is part of a long line of if...elseif...else statment block where I am parsing a command as entered via a PHP CLI.

I hate the formatting. It follows the PSR, but it's still no fun to read.

Can anyone offer suggestions on how to clean this up so it is hyper-readable? Code runs perfectly, but it is hard to visually distguish where one set of code for a command ends and the next one starts.

Notes:
$cmd = an object, which has methods for parsing and cleaning up commands.

User generated image
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DrDamnit

ASKER

This shows my python side coming through where strings as objects are quite handy.

Do you have a link our example of an appropriate RESTful interface here?
Yeah, Ruby on Rails treats everything as an object with its own sets of properties -- very handy.  But in PHP we have to call functions to discern the characteristics like strlen().

See if this helps:
http://www.programmableweb.com/news/how-to-build-restful-apis-using-php-and-laravel/how-to/2014/08/13

Here is my (years old) take on APIs
https://www.experts-exchange.com/articles/12239/Introduction-to-Application-Programming-Interfaces.html
Somehow, I think we're talking past each other.

Based on your answers (and my understanding) an API is generally accessed over HTTP. We use SOAP (*shudder*) or REST as the structure / style.

But my question is related to cleaning up code that can be typed into a CLI, and which uses direct interactions with PHP and the database.

Once such CLI command might be:

users find byemail someone@somewhere.com.

This is processed by the Command class.

The "startsWith" is how I am figuring out what class of command has been given. Because these are all valid, but do different things:

users find byemail someone@somewhere.com
users find byfirst ray
users find bylast paseur

Thus, if it starts with "users find", I know I am going to output the same thing, but the only difference is the WHERE statement in the query that finds these users.

Based on your feedback, and reading about CRAP, I ended up refactoring a lot of the code into their own functions, which makes this read better and got rid of the nested if statements:

User generated image
But I am just not making the connection on how a RESTful style API would be applicable or relevant. Am I missing something?
For reference, this is the Command class. (Posted because I think it is causing some confusion. I am well aware that PHP requires strlen() to get a string length).
command.class.php.txt