Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

My PHP Best Practices

DZone's Guide to

My PHP Best Practices

· Web Dev Zone
Free Resource

Add user login and MFA to your next project in minutes. Create a free Okta developer account, drop in one of our SDKs to your application and get back to building.

PHP's greatest strength is also its greatest weakness. Flexibility.There are an infinite number of ways to perform the same task which PHPwill happily do without so much as a peep as to how poor the codereally is. Sadly, most developers endure a trial by fire where theyonly learn from their mistakes after it's too late.

I suggest a more retro-active approach. Studying, surrounding, andforcing yourself to abide by best-practice coding standards will yieldsurprising results in your applications despite the fact that it mayseem like more work than it's worth.

I've come up with a list of things that I feel are most important to me when it comes to coding. So, without further adieu:

1) Always develop with error reporting set at E_ALL and E_STRICT.

Using E_STRICT seems to be somewhatcontroversial, but I can't tell you how many times its saved my butt.Some of the notices and warnings it gives you may seem trivial atfirst, but later on down the road their value becomes obvious. Itreveals holes in your code that you may not initially notice andtherefore gives you a reassuring sense that the script/application iscloser to being rock solid. 

2) Keep efficiency/speed in mind

This area is a major problem withupcoming developers. It's easy to get so tangled up in 'Just making thedamn think work' that you lose sight of exactly what you're doing andhow inefficient it really is. There are countless ways to accomplishthe same task in PHP, but only a few stand-out above the rest when itcomes to cpu-cycles.

[img_assist|nid=6155|title=|desc=|link=none|align=right|width=200|height=152]

My go-to site when contemplating one method over another is http://www.phpbench.com/.Chris has set up this page to calculate the cost of different methodsand compare them each time the page is loaded. Go ahead and refresh thepage, you'll notice some of the times and percentages have changedslightly.

If nothing comes to me right away, I'llskip it and go onto the next ask. Never let yourself get held up byefficiency problems. You can always come back later with profiling andidentify the problem areas. Keep yourself focus on the project and thetasks ahead instead of worrying about efficiency all the time, butdon't ignore it completely.

Helpful Links:
63+ best practice to optimize PHP code performances
PHP Performance Best Practices

UPDATE: Loic Hoguin pointed out that one's time and effort may bebetter spent elseware. He has a point in the sense that it's not worthit to change all your prints to echo accross your application. What Iwas trying to say is that you should always be aware of otheralternatives to the code your writing, especially in loops and commonplaces where bottlenecks occur. Don't let it take a high priority whiledeveloping but don't completely ignore it either. Most things can beidentified and fixed during profiling (see below) but you could makethings a little easier with some foresight now.

3) Portability, Portability, Portability!

Write code on a Linux/Apache/MySQLenvironment like you plan on moving it to a Windows/IIS/MSSQL platform.I know it sounds absurd but you will be pleasantly surprised when thissort of nightmare comes true. Done right, it will take about 1/100th ofthe time to convert everything than it would had things been writtenpoorly for a very specific environment.

Utilize config files that are laid outwith your client's sanity in-mind. Keep things simple, well-commented,and place the most-edited content near the top. No one likes siftingthrough a thousand lines just to find some database connectioninformation. 

4) Don't over-think!

This may seem contrary to some of theother tips here, but keep things simple whenever possible. Somethingthat irks me is when I see a preg_replace() function used when a simplestr_replace() would have worked perfectly. This goes back to theefficiency tips, but while regular expressions are much more versatile,they're also much slower. So, when given an opportunity to makesomething much more complicated than it needs to be, instead of showingoff, just get the job done.

Helpful Links:
Ten PHP Best Practices Tips that will get you a job 

5) Utilize 3rd party software

Debugging - I wrote an article about How XDebug will make you believe in God.The way it formats debug data and prints out pertinent scopeinformation makes it an extraordinary tool when trying to squash bugsand quirks in your code. 

[img_assist|nid=6156|title=|desc=|link=none|align=right|width=200|height=125]

Profiling - For somereason, profiling is my favorite part of programming, and, in myopinion, the most overlooked aspect of the development cycle. XDebughas the ability to generate profile reports which can be decipheredfrom a variety of programs. I use and love WebGrind because I can use it from any PC and don't have to run any executables. Popular alternatives are KCacheGrind for linux and WinCacheGrind.KCacheGrind is extremely feature-rich and powerful while I've foundWinCacheGrind to be somewhat buggy. I prefer WebGrind because itpresents the data very plainly but easy to understand and makesspotting the bottlenecks much easier. Seeing a page load 5000% fasterbecause I stupidly put a db-connection function in the wrong placewarms my heart.

PHPUnit - Popular unit-testing software. Find more info here: http://phpunit.sourceforge.net/

Helpful Links:

Best practices in PHP development  

6) Set, and stick to, naming conventions and coding styles

Clean code starts with laying down anaming convention and sticking to it. That means having a scheme forfunction, variable, class, and constants. Not only will this help youcode more quickly because you don't have to go running around toremember how you named that last database object, but your code willappear much more sleek and professional. Of course the style you use isa matter of personal preference, but check out Zend and Pear to see howthey handle things.

function myFunction($my_var) {  
}
// Which is better?
function my_function($myVar)
{
}

Neither is better, just pick a reasonable convention and stick to it.

7) Validate & Sanitize your Inputs!

I've seen more articles on PHP SQL injection prevention than any other subject. Which means it must still be happening to a great many number of people. When it comes to security, it's always safe to assume that some hellion out there is hell-bent on ruining your day. Take the time to make sure your inputs are in the data-type you are expecting and sanitize them for any hostile characters before using them.

// Query  
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));

Using sprintf() and mysql_real_escape_string() are great habits to get into, but be weary about overusing sprintf() when you don't have to. In some cases it isn't necessary and its slower than normal string concatenation.

if (isset($myVar) && is_array($myVar)) {  
// GOOD
}
if ($myVar) {
// BAD
}

 

Always use isset() or empty() before checking for type because is_array() is costly and could waste many valuable cpu-cycles if the variable isn't even set in the first place. Short-circuit is your best friend when it comes to efficient programming.

The latter example will throw all kinds of notices and warnings if the variable isn't even set. Not to mention that this leaves you vulnerable for an array of different attacks.

Helpful Links:
Web Application Best Practices

8) Surround yourself with people who know more than you.

Some people have a problem with insecurity, but I can say from first-hand experience that there is no better way to improve yourself by leaching off the kindness of others. No really, working around those who have experience while conducting yourself properly will yield all sorts of benefits. Humility is a great thing.

Never stop learning!

Any best-practice list can never be complete. There is far, far, too much to cover. The most helpful tip I can offer is to always be on the lookout for resources out there that you can benefit from whether it be on the web, books, or through other people. Complacency is not acceptable in the development-world.

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Published at DZone with permission of Mike Bernat, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}