July 31, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

PHP Coding Style and Organization

  • April 18, 2003
  • By Elizabeth Fulghum
  • Send Email »
  • More Articles »

Generally, programming is considered as something that happens behind the scenes; something that has more to do with function than form. Programmers frequently leave the appearance of the application up to a designer, so the idea of style having anything to do with coding can seem a little laughable at first. After all, as long as the logic and syntax of a PHP script is correct, the computer knows what we mean, and our script works. The computer doesn't care what the actual code looks like, only what it says.

But the computer only processes scripts; people are the ones who conceive and author them. Besides just "working," it is essential that an application is maintainable, re-usable, and most importantly, expandable. It has to be readable and understandable not only to the person who authored it, but to other people as well.

In this article, you'll find some general ideas on the elements of good programming style, quick tips for achieving it, and also some thoughts on how to organize the code within your scripts.

Comment Your Code

Comments are worth mentioning first, because their usage is the single most important aspect of coding style. Ironically, it also seems to be the one rule of good style that everyone forgets either by accident, or by tacit decision that it's really more effort than it's worth.

Comments, however, exist for a valuable reason. Even the most logically coded script is still, essentially, written in a foreign language of variables, loops, and functions. Comments give you a road map to what's happening in the script at any point and time. This is not so important while you are writing the script, because much of the material is fresh in your mind. It is, however, a life saver if you ever need to return to something you wrote several months ago. Spending a half hour attempting to understand what you wrote before you can actually accomplish anything is always a bad situation to be in.

Because coding methods can vary from programmer to programmer, comments also aid in making your programming instantly more understandable to anyone else who needs to access it. In multi-developer environments, this is essential to being able to effectively share or hand code down to another programmer.

Commenting your code is also good method of re-affirming your understanding how your own script works. When dealing with particularly complex applications, it is easy to lose track of the logic or flow of the script. Including comments on what each piece of code does not only encourages you to think about what's happening, but can often highlight problems or potential bugs along the way.

Indent Your Code

Commenting your code goes a long way to making it more understandable, but what about making it more readable? Take a look at the following two snippets of PHP, both of which produce the same output (this code snippet dynamic generates form fields based on information pulled from a database). Which is actually easier to read?

switch($row['type']) {
case 'textfield':
$formfield = '<tr><td class="formbg1"><b>'.$row['name'].':</b></td><td class="formbg2"><input type="text" name="customfields['.$row['id'].']" maxlength="'.$row['maxlength'].'" size="'.$row['maxlength'].'" value="'.$value.'"></td></tr>'."\n";
break;

case 'list':
$values=explode(',',$row['values']);
$formfield = '<tr><td class="formbg1"><b>'.$row['name'].':</b></td><td class="formbg2"><select name="customfields['.$row['id'].']"><option value="">Select One</option>'."\n";

foreach($values as $val) {
if ($value==$val) { $selected = " selected"; } else { $selected = ""; }
$formfield .= '<option value="'.$val.'"'.$selected.'>'.$val.'</option>'."\n";
}
$formfield .= '</select>'.$fields['field1'].'</td></tr>'."\n";
break;
}


switch($row['type']) {
    case 'textfield':
$formfield = '<tr><td class="formbg1"><b>'.$row['name'].':</b></td> <td class="formbg2"><input type="text" name="customfields['.$row['id'].']" maxlength="'.$row['maxlength'].' " size="'.$row['maxlength'].'" value="'.$value.'"></td></tr>'."\n";
break;

case 'list': $values=explode(',',$row['values']); $formfield = '<tr><td class="formbg1"> <b>'.$row['name'].':</b></td><td class="formbg2"> <select name="customfields['.$row['id'].']"> <option value="">Select One</option>'."\n";
foreach($values as $val) { if ($value==$val) { $selected = " selected"; } else { $selected = ""; } $formfield .= '<option value="'.$val.'"'.$selected.'>'.$val.' </option>'."\n"; } $formfield .= '</select>'.$fields['field1'].'</td></tr>'."\n";
break;
}

Just as in HTML, indenting in PHP makes a script easier to follow. The general rule for indenting goes like this: all statements within control structures (if..else.., while, foreach, switch, and so forth) should be indented one unit. The typical "unit" consists of 4 spaces, though some people prefer to use a single tab or an alternate number of spaces.

Modularize Scripts

When the term modularization is used in the context of programming, it refers to the process of breaking a large application up into separate parts, or "modules," that perform specific jobs. For example, if you were building an address book application, you might have one script that allowed users to view addresses, another to allow a new user to be added, another to handle edits, and a final one for deletions. This type of a modular coding is a first step—good programmers take it farther.

When you begin writing a script, you will find that certain blocks of code are frequently re-used. Common tasks like connecting to databases, validating user input, and checking a user's login information can occur multiple times throughout the scripts of a complete application. Initially, the inclination might be to copy and paste your code block to wherever it happens to be needed. But, this gets messy; if you need to alter the code block in one script, you're condemned to updating it everywhere else it occurs.

Here, modular programming moves to the next level.

Typically, programmers will create one or more shared files at the beginning of the programming process. In almost every case, there is a least one file (often called global.php or lib.php) that contains any functions or classes that are used multiple times throughout an application. In addition, there may be a separate file that is used to store configuration variables for the script. Often times, these are variables that would need to be changed if a script was being distributed or moved from server to server (such as directory names, or database login information, and so forth). By condensing them into a single, separate file, the process of updating them becomes significantly easier. It also eliminates the need to comb through individual script files to make changes.

These "global" files can be shared among all the other scripts in the application by including them using the include() or require() functions. Once they are included, any of the functions or variables within them can be used as though they were part of the running script itself.





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel