Categories


Loading feed
Loading feed
Loading feed

Three Quick Tips To Make Your PHP Understandable


Introduction

Producing code that clearly conveys a developer's intent is key to any well written application. That not only applies to PHP, but every programming language. Developers who emphasize the creation of legible code tend to create applications which are easier to both maintain and expand upon. After seven years of programming in PHP I've worked on a variety of projects where well organized and legible code were set aside for numerous reasons. Some of those reasons include time constraints, lack of experience, lost enthusiasm, misdirected pre-optimizing, and the list goes on.

Today we'll look at three simple methods which are commonly ignored by developers for some, if not all of the reasons described above. First, we'll discuss the importance of clean conditional logic. Second, we'll look at how you can cleanly output blocks html of in PHP. And finally, we'll examine the use of sprintf to convey variables placed in stings more legibally.

Tip #1: Write Clean Logic Statements

Example 1.1: Unclean Conditional Logic
<?php
if($userLoggedIn) {
   // Hundreds of lines of code
}else{
   exit();
}
?>

The above statement seems straight forward, but it's flawed for the reason that the developer is giving this conditional block too much responsibility. I know that might sound a little weird, but stay with me.

The type of conditional organization above makes for unnecessarily complex code to both interpret and maintain. A brace that's paired with a control structure hundreds of lines above it won't always be intuitive for developers to locate. I prefer the style of conditional logic in example 1.2, which inversely solves the previous example. Let's take a look.

Example 1.2: Clean Conditional Logic
<?php

if(!$userLoggedIn) {
    exit();

}

// Hundreds of lines of code

?>

This conditional statement is more concise and easier to understand. Instead of stating: "if my condition is met, perform hundreds of operations, else exit the script", it's saying "if my condition is not met, exit the script. Otherwise, I don't care about what happens after that. I am only concerned with stopping execution". So, by doing this, you've limited the operations that a given control structure has been tasked with, and that will help other developers quickly understand your code.

Tip #2: Use Less PHP And More HTML With Alternative Syntax

When PHP is tightly intertwined with HTML it can be awful to lay your eyes upon. Many years ago, while with a previous employer, the development staff and I believed it was a sin to use straight HTML in PHP files. We believed every file ending in a .php extension could only contain PHP. In retrospect, I don't know why we ever did this, but I have seen other groups adhere to such rules as well. This style made what should have been simple HTML far more complex that it had to be.

Over the past few years the style in which developers are writing PHP to output HTML has shifted quite a bit. Let's look at Example 2.1

Example 2.1: No Alternative Syntax, and a Lot of PHP.
<?php
echo "<table size=\"100\">\n";
echo " <tbody>\n";

if($displayResults) {

     while($row = mysql_fetch_assoc($result)) { ?>
         echo "<tr>\n";
         echo "<td>" . htmlentities($row['id']) . "</td>\n";
         echo "</tr>\n";
     }

}

echo "</tbody>\n";
echo "</table>\n";

?>

This is typical to what I've seen in a number of PHP applications. Though this is a simple example, I am sure you can appreciate how this method of outputting mostly html can grow out of control. It requires significantly more developer brain power to determine the code's purpose than the example below.

Example 2.2: Less PHP Paired With Alternative Syntax
<table>
    <tbody>
    <?php if($displayResults): ?>
    <?php while($row = mysql_fetch_assoc($result)): ?>
       <tr>
          <td><?php echo htmlentities($row['id']); ?></td>
       </tr>
    <?php endwhile; ?>
    <?php endif; ?>
    </tbody>
</table>

Here in example 2.2 the same functionality is achieved by using PHP alternate syntax and less output statements. As you can see, this fashion of interweaving PHP and HTML can go a long way to increase code readability.

Tip #3: Use "sprintf" and Friends

Example 3.1: Uncleanly Spliced String.
<?php

$sql = "SELECT col1, col2, col3 FROM people WHERE first_name = '" . mysql_real_escape_string($first_name) . "' AND last_name = '" . mysql_real_escape_string($last_name) . "'AND foo = '" . ($bar = "good" ? "good" : "bad") . "' ORDER BY col1" ;

?>

I see these types of indecipherable strings --like this SQL statement example-- all too frequently. The meaning of this query has been lost due to numerous concatenations and escape functions; which means developers have to invest a significant amount of time to comprehend the code.

In order to avoid this this, I use PHP's sprintf() function. sprintf() is a function that's part of a family of functions --referred to as the "printf" family of function-- that substitute designated tokens with arguments to the function. For example, let's look at the code in example 3.2.

Example 3.2: Cleanly Assembled String With sprintf()
<?php

$sql = 'SELECT col1, col2, col3 ' .
             'FROM people ' .
             'WHERE first_name = "%s" ' .
                 'AND last_name = "%s" ' .
                 'AND foo = "%s" ' .
             'ORDER BY col1 ';


$sql = sprintf($sql, mysql_real_escape_string($first_name),
                           mysql_real_escape_string($last_name),
                           ($bar = "good" ? "good" : "bad"));

?>

This method allows developers to regain a sense of the data that they're representing. In this particular example the %s token means replace with a string. There a number tokens such as %d (decimal) and %f (floating point).

Check out PHP's sprintf manual page for a more detailed account of what you can do with the "printf" family of functions.

Conclusion

I hope this article has provided some information you find useful. Making your PHP easy to understand by others should be a top priority for every developer, and I believe that these three simple tips can serve as a start on that journey.

Comments


Tuesday, June 24, 2008
PDO OR ZEND_DB INSTEAD OF MYSQL_REAL_ESCAPE_STRING
7:09AM PDT · foundline
PLEASE, DON'T EVER DO THIS.
7:12AM PDT · wechsler
RE: PLEASE, DON'T EVER DO THIS.
8:02AM PDT · dom29399
THINK YOU MISSED THE POINT...
8:13AM PDT · Nozavroni
PLEASE UNDERSTAND MVC BEFORE COMMENTING
8:59AM PDT · kenleycapps
SINGLE EXIT PRINCIPLE
11:59AM PDT · Brad Harris [unregistered]
Wednesday, June 25, 2008
DOT LANGUAGE IN PHP TO HELP WITH READABILITY
12:45AM PDT · philip142au
MIXED BAG
9:35AM PDT · watchmaker
REGARDING POINT ONE
10:50AM PDT · escindex
Sunday, June 29, 2008
NEGATIVE LOGIC SHOULD BE USED WITH CARE
2:57PM PDT · spqr_ca
Tuesday, July 1, 2008
HEREDOC
12:50AM PDT · tibobeijen
Wednesday, July 9, 2008
ABOUT MANIPULATION OF INPUT
7:56PM PDT · Anonymous User [unregistered]
Monday, July 21, 2008
NO, JUST... NO.
3:02PM PDT · bugmenot5
Wednesday, August 6, 2008
HEREDOC IS GOOD! AND SO WILL NOWDOC BE TOO :)
5:23AM PDT · ajogden
Thursday, August 7, 2008
TIP #2
12:19PM PDT · scinco