Refactoring PHP

Here are some common opportunities for improving the maintainability of code through refactoring that I find when reading code.

  1. Replace Duplicated HTML with Iterating Over an Array

    The purpose of most PHP code is to output HTML that the web server will send back to the browser. If you have a table that has 20 rows, and all those rows have the same structure, but the data in each row is different, you could write it 2 ways:

    1. Duplicated HTML

           <tr>
             <td align="center" valign="middle" class="messageFormTd3">2010-05-04</td>
             <td align="center" valign="middle" class="messageFormTd3">Copenhagen</td>
             <td align="left" valign="top" class="messageFormTd3">City Hall</td>
             <td align="center" class="messageFormTd5">10:15</td>
           </tr>
           <tr>
             <td align="center" valign="middle" class="messageFormTd3">2010-05-02</td>
             <td align="center" valign="middle" class="messageFormTd3">Zagreb</td>
             <td align="left" valign="top" class="messageFormTd3">Main Square</td>
             <td align="center" class="messageFormTd5">12:30</td>
           </tr>
    2. Iterating Over an Array

                 <?php foreach (array(
                   array('date' => '2010-05-04', 'city' => 'Copenhagen', 'venue' => 'City Hall', 'time' => '10:15'),
                   array('date' => '2010-05-02', 'city' => 'Zagreb', 'venue' => 'Main Square', 'time' => '12:30'),
                 ) as $event) { ?>
                 <tr>
                   <td align="center" valign="middle" class="messageFormTd3"><?php echo $event['date'] ?></td>
                   <td align="center" valign="middle" class="messageFormTd3"><?php echo $event['city'] ?></td>
                   <td align="left" valign="top" class="messageFormTd3"><?php echo $event['venue'] ?></td>
                   <td align="center" class="messageFormTd5"><?php echo $event['time'] ?></td>
                 </tr>
                 <?php } ?>
Advertisements

Published by

Dan Bernardic

A Winnipeg Web programmer. Member of the FarmLink Marketing Solutions and Farm At Hand team. Experienced with Web technologies, e.g. HTML5, CSS, ( Server-side ) JS, PHP, WordPress, MVC, etc.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s