How To Write Better Php Code These 7 Ways

You don’t need to remember functions, classes and specific solutions to be a good programmer. They are online, accessible at any time. And being a PHP developer you are unlikely to do much important work without being connected to the internet. Then what makes a good programmer? For me a good PHP programmer means someone who is efficient – who can solve problems and build quality web based software quickly and in a way that allows easier maintenance and extending of the program.

So being a good PHP programmer means mostly to write a good code with less effort and time spent. And here is what does that mean – several main things:

– Code that is short. I don’t mean putting everything on one line like some Perl coders do, but writing less waste, reusing code and keeping it modular
– Code that is easy to maintain and extend – this again means modular, but also a well commented PHP code.
– Code that doesn’t overload the server – you shouldn’t get obsessed by this but it’s important to keep the server overload low

How to write such code? There isn’t a specific recipe – every developer has its own style regardless the fact that many use frameworks or follow specific guidelines. So I’m not going to offer you a recipe. Instead of that here are seven of the best practices I follow to write better PHP (and not only PHP) code. If you use them too, you can drastically improve your efficiency as a developer.

1. Use alternative PHP syntax in templates:
I really hope you use templates, to begin with. If you are messing the HTML output directly into your scripts, you need to work on this first. If you already follow the concept to separate your design from the program logic, you are either using some template engine (usually a dead end reducing productivity) or placing a bit of PHP code inside the templates (loops, if/else statements etc). You can add some more cleanness to your views by using the alternative PHP syntax instead of the standard one with “{” and “}”. Using foreach: / endforeach;, if: endif; for: endfor, etc. keeps the PHP code on less lines in the view, helps knowing when a loop is opened and closed and generally looks better.

You can learn more about the alternative PHP syntax on the official PHP site – just search for “Alternative syntax for control structures”.

2. Everything capsulated:
You know about the DRY, don’t you? Don’t Repeat Yourself. Don’t copy-paste code. Always use functions and classes that will encapsulate often executed tasks. I know this is ABC of programming, but are you really really doing it? If one SQL query or code block is repeating itself 3 or more times in the application, then it should be a method or function. If it is repeating itself with slight variations, it should be a method or function as well (one that takes arguments). Here is what encapsulation gives you:

– less code, less writing
– ability to make changes across the entire app with a single code change
– clean and understandable code

These three things really make a better code. Let’s get a very simple example: which you think is better – formatting the date in the SQL query or in the PHP code? Both are fine if you encapsulate the format. If you use the standard PHP date() function everywhere or the SQL date formatting function, passing the format that the client requires, to each call, what will happen if the client wants a change? You’ll have to change it everywhere. To avoid that, build your own function to format the date or just put the formatting string (the “Y/m/d H:i A” thing for example) in a constant, so you can change it any time.

3. Use a DB object:
There are many ways to handle this, including ODBC, PDO and others. Whatever you do, don’t put mysql_query() or mssql_query() (or whatever) directly in your code. It’s not that you are going to change the DB engine ten times in the project – in fact in eight years in web development I had to change the DB engine of an existing project just a couple of times. It’s again about keeping the code short, readable and better. For example I have a DB object with methods that return a single value, single array or multiple array from a DB query. This way instead of writing:

$sql=”SELECT * FROM some_table”;
$result=mysql_query($sql);

and then using $result in some construction like while($row=mysql_fetch_array($result)), I just write:

$sql=”SELECT * FROM some_table”;
$some_things=$DB->aq($sql);

And I have the result in $some_things. (Note: don’t use this when retrieving thousands of records at once, it will exhaust the server memory).

4. Use CRUD Functions:
Just in case you don’t know, CRUD comes from CReate, Update, Delete. Create functions or object methods which will do this work for you or use the well known ActiveRecord. Do this instead of writing long SQL queries with tens of fields listed. This is going to save you a lot of time. It’s going to work automatically when you add or remove a field in the HTML form. Isn’t that great?

5. Debugging is your best friend:
Ok this point isn’t directly related to writing a better code – it’s more related to being a better programmer however. If something doesn’t work, you are not likely to fix it just by thinking hard or by looking at hundreds of lines of code. It’s not going to happen by swearing either. It’s going to happen by debugging.

Debugging is the action of going back following the logic of your program and finding the place where it works wrong or doesn’t work. It doesn’t matter if you use a debugger or just print_r() and echo() in various places of your code. The important thing is to trace backwards. Start from the current place – is there something wrong in it? If yes, go back few lines before the output/result happens. Is it still wrong? If yes, keep going few lines back. If no, then you know where exactly is the wrong piece of code – after this current line and before the line when your latest “is it wrong?” test returned true. I may sound bold, but I’ll say that this is the most important skill in programming (and not only) ever: to be able to go back and trace the route of the problem. If you learn to do this, you will be able to solve any solvable problem.

6. Mind the names:
A code that uses meaningful variable names is so much better – at any time you read it you know what is happening – is there a product currently modified, is it an array of users, is it the ID of the logged in, or is it anything else. I am not talking about Hungarian notation – just use variable names which correspond to the subject they represent and show whether it’s in singular or plural form. Don’t use variable names like $rows, $row, $varArr etc. Instead of that use $products when you are working with products, use $user when you are working with a single user, use $is_logged or $isLogged when you need a boolean variable showing whether the user is logged in the system. Use names that matter and be consistent in that. You’ll thank yourself later for writing such code. Other developers will thank you too.

7. Reduce DB queries:
It’s a common sense, but how many developers really do it? How many of them spend hours improving some unimportant thing like moving a sizeof() out of a loop and at the same time send a DB query in the very same loop? DB queries are the most server power consuming task in many web applications. Here are several ways to reduce the number of queries in your code:

– Use joins and left joins.
– Use inner selects when joins and left joins won’t do the job.
– Use views and temporary tables.
– Sometimes you’ll need to check something for a number of records and the previous three solutions won’t work. Instead of running a query each time, isn’t it possible to run one query for collection A, one for collection B and then use a foreach loop in PHP to check the condition? Very often it is. Be creative.

Reducing the number of queries is vital for web applications that are going to be used by many users at the same time. Sometimes you may need to sacrifice code shortness for that. This will not make your code worse – you should give the things their correct priority.

Are you following any of these guidelines in your code now?