Writing Solid PHP Code 2 - Naming and Style

January 26, 2009 by admin  
Filed under Articles, PHP

Having a consistent style makes your PHP code more readable and maintainable. Even in projects where you are the only programmer, once the project progresses to a certain size it can become difficult to maintain.

Variable Names

Variable names should be very descriptive. They should give anyone that is not familiar with your script to understand what its for without much digging.

Variable names should all follow the same conventions. It doesn't matter if you use camel casing (YourVariableName), lower camel case (yourFunctionName), or underscores (your_variable_name), as long as all the variable names have the same style.

It is a good idea to include the scope of the variable in the name. For example, if you have a function or set of functions dedicated to parsing a string you may want to start the variable name with "parse."

Function Names

Function names should also be very descriptive and follow a defined convention. Function names should be prefixed with the unit they are in. For example, if you have a file named databaseFunctions.php you might prefix all the functions within that file with dbFuncs_ or something similar.

Function names should describe the action taking place. For example, instead of "StringParser()" use "ParseString()."

Indentation

Indentation is very important as it makes reading the code easier. Proper indentation can help you keep track of loops, conditional statements, and blocks of code. Each level should be indented a step further. The following snippet is a good example of proper indentation:

<?php
    $loopVariable = 35;
    for ($loopCounter = 1; $loopCounter < 25; $loopCounter++)
    {
        $loopVariable = $loopVariable*$loopCounter;
        if (($loopVariable % 2) == 1)
        {
            echo "Even<br >n";
        }
    }
?>

Using good techniques such as proper naming and indentation may seem unneccesary for small projects. However, for larger projects it is essential for writing maintainable code.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati

Writing Solid PHP Code 1 - Error Handling

January 20, 2009 by admin  
Filed under Articles, PHP

This is the first in a multiple part series on writing solid PHP code. By solid I mean fast, efficient, maintainable and secure code.

This first article deals with error handling. Error handling can stop problems in your application early in their tracks and take appropriate action. Error handling has the added benefit of adding professionalism and also making debugging easier.

Error handling should be applied to any action that has the possibility of failing. Failures in your application are often the result of some unexpected user input, user input should hence always be checked for vailidity.

The most simplistic way of employing error handling is using die(). die() takes a single string argument that it will output and then terminate the script.

Example:

<?php
mysql_connect("localhost", "root", "password") or die(mysql_error());
echo "Connected to MySQL the MySQL server! <br \>";
mysql_select_db("dbtable") or die(mysql_error());
echo "Connected to Database";
?>

The above example tries to connect to a database, and produces the MySQL error if it failed. It then tries to select a table within the database and also produces the MySQL error if it fails. These are both actions that could fail for many reasons: the connection to the the login information could be incorrect, the connection to the database could be lost, or the table might not exist. Even in this short example there are many reasons why it could potentially fail.

Since this example does only two things, it is okay to terminate the script upon failure. If we have a larger script, however, we may want to note the error and continue running. This is where die() falls short, not only can we not continue executing but the message is outputted to the page. If our script produces an error we want to log it for the administrator to view later as well as keep it hidden from our users.

<?php
mysql_connect("localhost", "root", "password") or trigger_error(mysql_error(), E_USER_ERROR);
echo "Connected to MySQL the MySQL server! <br \>";
mysql_select_db("dbtable") or trigger_error(mysql_error(), E_USER_ERROR);
echo "Connected to Database";
?>

This example uses the trigger_error() function to throw the error. An error will terminate the script while warnings and notices will allow the script to continue running. Below is a list of types of errors you can throw with trigger_error(). Also note an error can have multiple error types.

  • E_WARNING
  • E_NOTICE
  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE

For a full list, visit the PHP documentation. Note that not all of the error types in the PHP documentation can be used with trigger_error().

For some errors, notices, and warnings will be outputted to the page. This is good for debugging but bad for live sites. To change this open your php.ini file in your php directory and search for the following line

display_errors = On

Change 'On' to 'Off' and save the configuration file and restart your web server. Make sure log_errors is set to 'On' so that all the errors are saved to a log file for you to review later.

Look for more articles on writing solid PHP code.

del.icio.us Digg Facebook Google reddit SlashDot StumbleUpon Technorati