45 users online (0 members and 45 guests)  


  Results 1 to 5 of 5

Related

  1. formatting text with PHP    Forum: HTML Forum
    Replies: 1
  2. Formatting in an IFRAME    Forum: CSS Forum
    Replies: 2
  3. help in formatting a query    Forum: PHP Forum
    Replies: 1
  4. Formatting Dates    Forum: HTML Forum
    Replies: 2
  5. Formatting with Html    Forum: HTML Forum
    Replies: 4
  1. #1
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    PHP Code Formatting and Design

    While programming PHP code (as well as other languages), I continuously come across code I cannot figure out. While some of this is due to my own lack of knowledge, many times it is due to the original programmer's inability to create readable and easily interpreted code. Every programmer hopes that they are the only ones that will ever see the code they are writing (known as job security). Unfortunately, this will inevitably not be the case. Whether the programmer retires, the client changes developers, or the code is released to the open-source community, others will read and try to imporove your code. As a professional courtesy (after all, you may get someone else's unreadable code and be expected to interpret it), all programmers should create their code such that others can read it and understand it without a Rosetta stone.

    During my research on imways to improve my own skills, I came across slides from a speach entitled "The Seven Steps to Better PHP Code". The link to the slides will be included at the end of this article.

    After reading through the slides, I realized that these steps, when followed, would keep many programmers from going bald or developing a twitch.

    The steps are:
    1. Consistently Format Source Code
    2. Establish Naming Conventions
    3. Create API Documenation
    4. Eliminate Redundant Code
    5. Shorten Code Blocks
    6. Separate Different Concerns
    7. Replace Implementations
    I will use the following code to demonstrate the steps:
    PHP Code:
    $q=$db->query('SELECT * from data ORDER BY '.$order);
    print 
    '<table><tr><td><b><a href="?sort=item">Item</a></b></td><td><b><a href="?sort=barcode">Barcode</a></b></td><td><b><a href="?sort=shelf">Shelf</a></b></td><td><b><a href="?sort=quantity">Quantity</a></b></td></tr>';
    while(
    $q->valid()){
    $r=$q->current(SQLITE_ASSOC);
    print 
    '<tr>';
    $first=true;
    foreach(
    $r as $key=>$value){
    if(
    $first){
    $item=$value;
    $first=false;}
    print 
    '<td>'.$value.'</td>';
    if(
    'quantity'==$key)$sum+=$value;}
    print 
    '<td>[<a href="?sort='.$order.'&action=add&item='.$item.'">+</a>]</td><td>[<a href="?sort='.$order.'&action=remove&item='.$item.'">-</a>]</td></tr>';
    $q->next();}
    print 
    '<tr><td></td><td></td><td>Total:</td><td><b>'.$sum.'</b></td></tr></table>'
    Step 1: Consistently Format Source Code

    The two most important things to do here are first to establish a standard. Items to include in the standard include:
    Indentation (When and How Far)
    Whitespace (whenlettersaresqueezedtogethertheyarehardtoread)
    Capitalization (thisMakesThings muchEasier toRead especiallyWhen combinedWith White Space)
    Second, and probably the most important, BE CONSISTENT!!!!!

    After formatting, the code looks a TON better:
    PHP Code:
    $q $db->query('SELECT * from data ORDER BY ' $order);
    print 
    '<table><tr><td><b><a href="?sort=item">Item</a></b></td><td><b><a href="?sort=barcode">Barcode</a></b></td><td><b><a href="?sort=shelf">Shelf</a></b></td><td><b><a href="?sort=quantity">Quantity</a></b></td></tr>';
    while (
    $q->valid())
    {
       
    $r $q->current(SQLITE_ASSOC);
       print 
    '<tr>';
       
    $first TRUE;
       foreach(
    $r as $key => $value)
       {
          if(
    $first)
          {
             
    $item $value;
             
    $first FALSE;
          }
          print 
    '<td>' $value '</td>';
          if(
    'quantity' == $key$sum += $value;
       }
       print 
    '<td>[<a href="?sort=' $order '&action=add&item=' $item '">+</a>]</td><td>[<a href="?sort=' $order '&action=remove&item=' $item '">-</a>]</td></tr>';
       
    $q->next();
    }
    print 
    '<tr><td></td><td></td><td>Total:</td><td><b>' $sum '</b></td></tr></table>'

    Step 2: Establish Naming Conventions

    The purpose of every variable should be able to be understood at a glance. The ways this can be done include:

    1. Establish a naming scheme
      1. Capitalization
      2. Consistent names
      3. Make the purpose clear
    2. Keep file names simple (alphanumeric chars, blanks, underscores)
    3. Prefix names in global namespace



    Step 3: Create API Documentation or DOCUMENT DOCUMENT DOCUMENT

    Every function that is publicly accessible should be described using a comment block. This primarily applies to Object-Oriented Programming, but also applies to any code that people will be interfacing with.

    An example of a comment block for a class would be:

    PHP Code:
    /**
     * This is what the class does.
     *
     * @package PackageName
     * @author Your Name
     * @version 1.0.0RC2
     */ 
    Functions themselves should have the following comments added:

    PHP Code:
    /**
     * @param $aBar the Bar
     * @param $aBaz the Baz
     * @return bool success
     */
    public function doFoo($aBar$aBaz
    The comments added to each function will allow each programmer that comes in to see what values are needed as well as what is returned. The comment blocks are also easily identified and do not need to be searched for.

    Step 4: Eliminate Redundant Code

    Imagine the headache if you are running the same calculation in multiple locations, and you find out that either the calculation is wrong or the customer needs it done differently. The first question you will need to ask yourself is: Where did I make that calculation again? Once you have made the changes in all 37 locations (or howeer many you ended up with), you need to ask the following question: Were there only 37 places I made the calculation?

    Instead, to both save on processing as well as allow you to get more haircuts (since you will not be going bald as quickly), pull the calculation out of the code into a function and then call the function whenever you need it.

    Step 5: Shorten Code Blocks

    A good rule of thumb for functions and methods is: If it will not fit on your screen without scrolling, it is too long.

    Also, every function should be able to be understood (maybe not in complete detail, but you get the picture) within the first 30 seconds of looking at it. If you have followed the above steps, your code will already be approching this threshold.

    Step 6: Seperate Different Concerns

    Seperate functionality. If you will be using the same code to add, modify, delete, update, reverse, twist, tangle, untangle, and subtract data, your code is doing too much, and future developers will never be able to understand it. Instead, pull out each differing function and create a section of code focusing on that alone. It will make the code easier to read and understand as well as update.

    For example, update the code above as follows:
    PHP Code:
    function get_data($aSort)
    {
        
    $db = new SQLiteDatabase('report.sqlite');
        
    $q $db->query('SELECT * from data ORDER BY ' $aSort);
        
    $result = array();
        while(
    $q->valid())
        {
            
    $result[] = $q->current(SQLITE_ASSOC);
            
    $q->next();
        }
        return 
    $result;
    }

    function 
    get_total()
    {
        
    $db = new SQLiteDatabase('report.sqlite');
        
    $q $db->query('SELECT SUM(quantity) from data');
        
    $result $q->current(SQLITE_NUM);
        return 
    $result[0];
    }

    print 
    '<table>';
    print 
    '<tr><td><b><a href="?sort=item">Item</a></b></td><td><b><a href="?sort=barcode">Barcode</a></b></td><td><b><a href="?sort=shelf">Shelf</a></b></td><td><b><a href="?sort=quantity">Quantity</a></b></td></tr>';
    foreach (
    get_data() as $r)
    {
        print 
    '<tr>';
        
    $first true;
        foreach (
    $r as $key => $value)
        {
            if (
    $first)
            {
                
    $item $value;
                
    $first false;
            }
            print 
    '<td>' $value '</td>';
        }
        print 
    '<td>[<a href="?sort=' $order '&action=add&item=' $item '">+</a>]</td><td>[<a href="?sort=' $order '&action=remove&item=' $item '">-</a>]</td>';
        print 
    '</tr>';
    }
    print 
    '<tr><td></td><td></td><td>Total:</td><td><b>' get_total() . '</b></td></tr></table>'
    Step 7: Replace Implementations

    One very important thing to remember is to try usig native PHP instead of an old extension. That way, the code can more easily be updated for future PHP versions. Imagine trying to get a bit of code working on PHP11 that is still using an extension that was written for PHP4. A pain, isn't it. On the other hand, it is a good idea to use the current extensions out there. They extend the functionality of PHP quite a bit, and will allow your code to look and function quite a bit better.



    Whether or not a developer uses all the recommendations listed above, using any of them will improve your code and allow both yourself and other developers to view your code and understand it.

    There is quite a bit of good information and resources located at www.refactoring.com

    The steps can be found at: http://inside.e-novative.de/uploads/TheSevenStepsToBetterPHPCode.pdf

  2. #2
    rangana's Avatar
    Moderator/Allstar

    Status
    Offline
    Join Date
    Feb 2008
    Location
    Cebu City Philippines
    Posts
    317

    Re: PHP Code Formatting and Design

    Well said. Sticked the thread. Keep up the good thoughts jthayne.
    Checkout my porfolio.
    Please click the button when a member helped you.
    Take time to use Forum's Search function.

  3. #3
    HTML's Avatar
    Administrator

    Status
    Offline
    Join Date
    Aug 2000
    Posts
    3,445

    Follow HTML On Twitter Add HTML on Facebook Add HTML on Google+ Add HTML on Linkedin Visit HTML's Youtube Channel

    Re: PHP Code Formatting and Design

    We need more posters like you guys.

    BTW jtahyne, what happened to the Aggies this year, My wife (horns) is dogging me all year.
    AHFBWEB Less customers per server, more power for you!

    Business Class Shared Hosting

  4. #4
    jthayne's Avatar

    Status
    Offline
    Join Date
    Aug 2008
    Location
    Texas
    Posts
    508

    Re: PHP Code Formatting and Design

    <Hangs Head> It is pretty embarassing, isn't it?

  5. #5
    DataPeople's Avatar
    New User

    Status
    Offline
    Join Date
    May 2010
    Location
    Dhaka, Bangladesh
    Posts
    1

    Re: PHP Code Formatting and Design

    Thanks for this informative post.



Tags for this Thread