beta it republik » Articles

Articles

Untitled Document
Thursday, 24 April 2008 | Article

Organized PHP Development

Programming is more than just writing code. It also requires some organization talent. This article will show you how to organize your project’s folder structure and present you a set of coding guidelines. You can take these guidelines and make them your own or build your own set of guidelines based on the ones in this article. It doesn’t matter if you follow these guidelines or others, the lesson you should learn from this article is, make sure you have guidelines and stick to them! Without guidelines code can become very difficult to read and the maintainability of your project will seriously decrease if not become impossible.


Introduction
Any web application can rapidly grow to a large number of files and code. Lack of organization in both files/folders structure and coding will seriously slow down your programming and decrease maintainability. It also wouldn’t be the first project to fail if you start programming without planning first. So think before you do is the message, but how? Where will you put all those files and how can you keep your code clean and readable?

Overview
It is important to be able to keep a clear overview of your project no matter how big it becomes. A clear folder structure and meaningful file names are vital to avoid your project from turning into a maze.

Keeping a global overview of your files and folders is one thing. You should also ensure that you write ‘easy to read’ code to increase maintainability. Coding guidelines are therefore a must. Your guidelines should outline rules for naming conventions of variables, constants, and function names. It should also make clear how you’ll handle indentation, spaces and quotes (single and double). And last, but not least, comment your code. Comments make it easy to understand what the code does for you or any other developer that might join your team, so you shouldn’t overlook them.



Getting your Folder Structure Right
A web application consists of many different file types, PHP files, HTML files, style sheets, images, XML files, XSLT files, and probably a lot more. In order to keep an overview over all these files it’s important to store them in an organised way.

I always start with the same basic folder structure. Any web application contains at least the same basic set of files—images, stylesheets, JavaScript, include files, and PHP files containing classes. I give my folders a short but meaningful name and, depending on the application, additional folders will have different names because they will store files with different functions or content. For example, if the web site has an administration tool to manage the site I call that folder ‘admin’ so I know that all the files in that folder shouldn’t bev publicly accessible.

File Names
The name of any file should give you a good clue of what’s inside. You will not name an image with a horse on it donkey. jpg!

Besides clear names for any file PHP files require a bit more attention. You have PHP files that will just output HTML but you will also have PHP files that will only be included in other PHP

files and you will also have PHP files containing classes. For these files I use the following naming convention:
  • my_file_name.php: will output HTML
  • my_file_name.inc.php: include file
  • my_file_name.class.php: class file

Programming best practices are like the traffic rules that we follow in our everyday lives. Just as how disobeying traffic rules can lead to an unholy snarl, not following coding rules will seriously slow down your programming and decrease the maintainability of your applications. Although it may be difficult to get started on following the generally accepted guidelines, you only stand to benefit from it ultimately.

The listing in Figure 1 makes a clear distinction between the different types of files. Drop them in their corresponding ‘inc’ and ‘class’ folders and you will never be confused about what they are.

It’s important to give all PHP files the .php file extension, whatever they contain. Some people give include files the .inc extension.


Fig 1: Basic Folder Structure


Now while this will perfectly work, if your Apache server isn’t configured correctly it will output the code as text to the browser if you call such a page directly. (Note: WhiIe your apache server may be installed correctly, someone else’s might not.)

Coding Guidelines and Why They are Important
Coding guidelines are a set of rules that define how you (and everybody else working on the same project) will handle all aspects of writing code in the same style. It goes from naming your variables to indentation and comments.

If you use coding guidelines you will see that your code becomes more readable to others and theirs to you. This will make you save a lot of time if you have to dive into someone else’s code. For yourself you will see the biggest benefit in reading your own old code after some time. In no time you will understand what you wrote previously and can amend it if necessary.

I think you have seen the benefits by now so let’s outline our coding guidelines.

Error Reporting
The following is not really a guideline but rather a help in clean programming.

You should turn on all error reporting while you develop. It will only help you write better code. Now you may say that you will have to initialize all your variables. I know, and we all know that’s a good practice. It’s not impossible to program PHP without any errors or notices.

In a production environment you shouldn’t output any errors to the screen but log them in a file invisible for your web site visitors. And errors will occur; scripts can’t handle every possible error, users are able of doing things beyond your imagination.

Naming Conventions
In the following sections, I’ll detail the naming conventions for:
  • Variable names
  • Constants
  • Loop indices
  • Function names
  • Function arguments
  • Code layout

Variable Names
What does the name of this variable tell you: $sUName? You can guess it has something to do with a name but there can be many types of names in any application. Second try: $user_ name. I think it cannot be clearer which value this variable will contain. This makes the most important thing about variable names crystal clear—make sure you can have at least an idea of what the variable will contain from its name.

It is recommended to make all your variables lower case and use an underscore to mimic a space. So $family_name is alright but avoid $FamilyName, $familyname, or $familyName. You can also use camelcase (concatena ting all words and start each word with a capital) to name variables. Please note the convention I propose is only one way of doing it. If you have another standard for naming your variables, please stick to it.

Further, developers sometimes give an indication to their variables of the type of value they will contain. Most people do this by starting the variable with a letter indicating the type (for example, an ‘s’ to indicate string). In managed code programming languages it might be a good idea but PHP is a typeless language (that is, a variable can contain any kind of value such as numeric, string, or boolean) so it isn’t necessary to follow this convention.

Constants
One of the reasons for choosing lowercase for variable names is making the distinction with constants. If you use uppercase for your constants (as PHP itself does) it makes a clear contrast with your variables.

Try to use constants wherever you need storing values that you don’t need to change. It’s not a good practice to use variables instead.

Listing 1
One Letter Variable Names in Loops

for( $i = 0;$i < count( $customers );$i++ )
{
echo $customers[$i];
for ( $j = 0;$j < count( $orders );$j++ )
echo $order[$j];
}
}


Loop Indices
You will often see the variable $i or any other single letter variable used in loops. Any loop within the first might have the name of the next letter in the alphabet. See Listing 1.

I recommend following this format because it makes your code a lot easier to read. This is the only exception you should make on meaningful variable names.

Function Names
A function works something out for you so it’s useful to give descriptive names to the functions (a verb in the name might help). For instance, the function encrypt_password($password) tells you exactly what it will do, whereas enc_pwd( $pwd ) is not that obvious.

Further, you can apply the same rules to variables and functions—keep your function names lower case and use underscores for spaces.

Function Arguments
Function arguments are just variables, so the same naming rules apply to them as well. The only thing you need to check for is how they are listed in the function and when you call the function. I use the same principle as in simple text writing—I leave a space after each comma before including the next variable, like this:

logon_user($user_name, $password, $ip_address)
Instead of:
logon_user($user_name,$password,$ip_address)



Listing 2
Where to drop the first brace?

//Option 1.
if( $this_is_the_way ) {
echo ‘Yes it is’;
}

//or

//Option 2.
if( $this_is_the_way )
{
echo ‘Yes it is’;
}



Code Layout
In the following section, I will detail the various aspects of code layout:
  • Braces
  • Spaces
  • Operator precedence
  • SQL code layout

Braces
This is an interesting one as I have seen people going into hot discussions over it. Will you put the first brace on the same line as the expression or not? Let’s look at Listing 2.

Listing 3
Correct indentation

while( $customer_country == ‘UK’ )
{
//Do this for any UK customer
if( $customer_name == ‘smith’ )
{
echo ‘Hello Smith from the UK’;
}
}


Listing 4
Spaces

//Example 1. Assigning values
$i=1;
$i = 1;

// Example 2. Conditional statements
if(($i==0)||($i==1))
if( ($i == 0) || ($i == 1) )

// Example 3. Calling functions
do_this($i,$j,$k)
do_this($i, $j, $k)



Listing 5
SQL queries

$query = “SELECT customer_name FROM tblcustomers WHERE customer_id = $customer_id”;



Have you spotted the difference? You surely did! What is the easiest to read? I would go for the second option; besides, most programmers prefer this option, although I must admit that I used the first option for a long time before I shifted to this easier format.

The next step is to ensure clear indention. The opening code using the braces should be at the same column as the opening and closing braces. Any code between the braces should be a tab to the right. See Listing 3 for an example.


The spacebar is probably the most used button on your keyboard and that’s probably the reason why they made it so large. While writing code, it’s important to use spaces properly to keep the code readable. There’s no better way to tackle this topic then with an example. See Listing 4 for the various code lines and their use of spaces. In each example the second line shows the best practice.

Operator Precedence
I struggled with using brackets at school because I kept forgetting the order of how to use them. In PHP, brackets are an excuse to not know the precedence! Use them wherever you can to make it crystal clear what’s going on. Of course, 5 + 3 * 9 or 5 + (3 * 9) does the same thing but I’m only convinced if I see the brackets.

SQL Code Layout
If the application has to access a database so you will need to write SQL queries. To make these statements easy to read capitalise all SQL keywords such as SELECT, FROM, UPDATE, INSERT, and DELETE. Leave all other words to their relevant case. If you don’t do this it might become difficult to distinguish SQL keywords from the other elements in the query.

Commenting Code
Comments are a very aspect of programming best practices. In 2002 I developed a web application for a customer of mine. I didn’t hear from him ever since the application went into production (I guess he was a happy customer). A few months ago he called me with a question about “this AJAX thing” he had heard of and if I could develop a few magical features to improve the user interface.

I had to read the old code and all the comments explaining what did what. After a few hours I was up and running to produce some more beautiful code.

Listing 6
Example of a top page comment

/**
*Class to access the MySQL database
*Author Dirk A. Hemelings
*Version 2.0
*Created 28/12/2005
*
*Functions:
*select_db ($db=’’)
*select ($sql)
*get_row ($result, $type=’MYSQL_ASSOC’)
*row_count ($result)
*select_one ($sql)
*insert ($table, $data, $debug=false)
*update ($table, $data, $where, $debug=false)
*
*/


Listing 7
Example of an ‘in page’ comment

/*Delete a customer if no record present
*$customer_id = unique id of the customer
*
*return : true if customer is deleted otherwise returns false
*/
function delete_customer($customer_id)
{
//Check if the customer has a record
$query = “SELECT customer_id FROM tbl…”
}


Listing 8
Quotes

//NOT good, double quotes no variables
$query = “SELECT * FROM tblcustomers”;

//Good, single quotes no variables
$query = ‘SELECT * FROM tblcustomers’;

//NOT good, will not even work
$str = ‘Your name is $customer_name’;

//Good, double quotes variables present
$str = “Your name is $customer_name”;



Without comments it would have taken me a lot longer to understand that four-year-old code. So where do you add comments? All your PHP pages should have a comment block to start with. This block should, at the very least, contain:
  • A description of what the page exactly does
  • Who wrote it (author names)
  • Version of the file
  • Creation date

In files containing PHP classes (or files containing many functions) it’s also recommended to add a list of the public functions and their parameters at the top. This will help you to quickly lookup a function and what parameters it requires. See Listing 6 for an example.

In the code file, you should add comments just before functions to explain what they do and what the parameters are (if any). It’s also a good practice to explain the possible return values of your function. Other places to add comments are code parts that do complex things. See Listing 7 for an example.

General Guidelines
In the following sections, I will detail some generic guidelines for:
  • Quoting strings
  • Shortcut constructs

Quoting Strings
Where should we use single quotes or double quotes? Both types of quotes are allowed in PHP but the parser will use variable interpolation (it will search the string for variables and replace them by their value) in double quoted strings. This means that you should only use double quotes if your string contains variables. If no variables are present you should use single quotes; otherwise, the parser will work for nothing. Another place where you need to use quotes are associative arrays. $fruits[‘apple’] is an example of an element in the ‘fruits’ array with key ‘apple’. You should use single quotes here and if you call a key with a variable you do it without quotes; for example, use $fruits[$fruit_key] and not $fruits[“$fruit_key”].

Shortcut Constructs
Shortcuts might be a good thing for operating systems; they are not always a good option in programming. Shortcut constructs (also called shorthand) are a shorter way for writing ‘if’ statements, by only using a question mark and colon on one line of code.

$boolean = $answer == ‘yes’ ? true : false;

This is the same as:

if($answer == ‘yes’)
{
$boolean = true;
}
else
{
$boolean = false;
}


Although the former option will save you many lines of code, I’d say the latter is easier to read. I use the first option only if the parameters are very short and the conditional statement is very simple.

It’s up to you to decide when you think it’s appropriate to use it or not but your code might be obfuscated if the condition is too complex.

Conclusion
Coding guidelines are a ‘must have’ for any developer, either working alone or in a team. They are like the traffic rules that we follow in our everyday lives. It keeps everything organized and everyone knows what to expect. If you work in a team, it becomes even more important to follow these rules. So you should sit down with your team before programming begins ensure everybody sticks to the same guidelines. If you work on your own, you can save yourself a lot of time by taking some time to start using coding guidelines. Ultimately, we only stand to benefit from keeping our code organized.


About the Author

Dirk Hemelings is a freelance developer with 15 years programming experience in various domains. Starting with desktop applications, he turned to web development in 1998. Ever since 90% of his projects are web applications or have been Web related. Dirk’s web development career started with ASP but he soon discovered PHP. Since then it has been his favourite scripting language.


   Related Links


Comment

Name:

Comment:

Captcha Verification !
captcha_image