2008.10.07

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

I suggest a more retro-active approach. Studying, surrounding, and forcing yourself to abide by best-practice coding standards will yield surprising results in your applications despite the fact that it may seem 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 somewhat controversial, 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 at first, but later on down the road their value becomes obvious. It reveals holes in your code that you may not initially notice and therefore gives you a reassuring sense that the script/application is closer to being rock solid.

 

2) Keep efficiency/speed in mind

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

PHP BenchmarkMy 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 methods and compare them each time the page is loaded. Go ahead and refresh the page, you'll notice some of the times and percentages have changed slightly.

If nothing comes to me right away, I'll skip it and go onto the next ask. Never let yourself get held up by efficiency problems. You can always come back later with profiling and identify the problem areas. Keep yourself focus on the project and the tasks ahead instead of worrying about efficiency all the time, but don'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 be better spent elseware. He has a point in the sense that it's not worth it to change all your prints to echo accross your application. What I was trying to say is that you should always be aware of other alternatives to the code your writing, especially in loops and common places where bottlenecks occur. Don't let it take a high priority while developing but don't completely ignore it either. Most things can be identified and fixed during profiling (see below) but you could make things a little easier with some foresight now.

 

3) Portability, Portability, Portability!

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

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

 

4) Don't over-think!

This may seem contrary to some of the other tips here, but keep things simple whenever possible. Something that irks me is when I see a preg_replace() function used when a simple str_replace() would have worked perfectly. This goes back to the efficiency tips, but while regular expressions are much more versatile, they're also much slower. So, when given an opportunity to make something much more complicated than it needs to be, instead of showing off, 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 scope information makes it an extraordinary tool when trying to squash bugs and quirks in your code.

webgrindProfiling - For some reason, profiling is my favorite part of programming, and, in my opinion, the most overlooked aspect of the development cycle. XDebug has the ability to generate profile reports which can be deciphered from 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 found WinCacheGrind to be somewhat buggy. I prefer WebGrind because it presents the data very plainly but easy to understand and makes spotting the bottlenecks much easier. Seeing a page load 5000% faster because I stupidly put a db-connection function in the wrong place warms 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 a naming convention and sticking to it. That means having a scheme for function, variable, class, and constants. Not only will this help you code more quickly because you don't have to go running around to remember how you named that last database object, but your code will appear much more sleek and professional. Of course the style you use is a matter of personal preference, but check out Zend and Pear to see how they handle things.

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.

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.

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.

Get my RSS Feed!

Comments

Loic Hoguin on (10.7.2008 4:55 pm) says

Sorry, but I must rant about point 2. There's 2 sides about optimization. The one you show is called micro-optimization, and it's the process of making a script run 0.00001s faster than before. That's hardly worth it. When you really want to optimize a website, a script or a function, the only thing that matters is its design. An example of optimization for a function could be to make a recursive function work iteratively, which is (usually) a lot faster. You talk a bit about profiling in your point 5, which is how you can find out what part of your script is slow and needs to be optimized. This is this profiling and how you use it to make your scripts efficient that should be in your point 2.

Also about filtering PHP has a filter extension that can validate about any data. It's in my opinion the best choice to filter data currently.

Good post, thanks for writing it!

 

Pablo Morales on (10.8.2008 1:17 am) says

Hi. 

Replace the point seven, enjoy your life, use Zend Framework :P

Cheers nice blog

 

kL on (10.8.2008 9:22 am) says

no. 7: isset($var) will hide your programming errors! Just check variable's value and let it throw notice if variable doesn't exist.

oh, and use PDO::prepare instead of mysql_bleh functions.

no. 2 is not a good idea. I'd recommend absolutely otherwise - don't keep efficiency in mind. 99% of time you won't run into problems (unless you're developer of flickr or such :). If you do, then profile and fix the bottleneck, but don't let occasional bottleneck skew your mind and get you obsessed about microoptimisations.

Absolutely nothing on phpbench matters. If you have O(n^2) algorithm, then fastest loops and quotes won't save you!

 

Dave on (10.8.2008 4:00 pm) says

The best argument I ever heard between using myFunction and my_function is that a developer without English as their native language will more easily be able to identify/translate different words when they are seperated with an underscore.

 

murshed ahmmad khan on (10.8.2008 10:45 pm) says

Right! Don't over-think! Keep it simple whenever possible, will let you deliver things faster and thus help you meeting the deadlines also.Just get the job done... may seem odd in some cases but it can ease your life.

 

Tedd Sperling on (10.10.2008 1:50 pm) says

I always find that number 8 is the easiest for me. It seems like everyone is.

Cheers,

tedd

 

Erik Hansen on (12.27.2008 3:07 am) says

On #5:  Zend Studio 6 also has a great debugger and profiler.  It costs $400, but it's worth every penny.

 

Taras on (1.9.2010 8:43 pm) says

Old post but I liked it a lot. Agreed with author in all 8 points. Great job!

 
* Name
* Email (Will not be displayed)
Website