Saturday, April 16, 2011

10 Best PHP Coding Style Practices

One the major problem for the beginners is the STYLE OF CODING, as it was for me as well. For some of the first few months I was stuck with the standards of different Frameworks and was following them and extracting the best of their styles. But short after I felt that, although they all are very different from each other but they have something in common, their Coding patterns. 

Lets Start.
  1. First of all Choose your favorite IDE. There are lots of PHP IDE in the markte, like NetBeans, Eclipse, PHPEdit, and lots more, Just Google :). As per my favorite I user NetBeans.

  2. Always user <?php ?>, to delimit PHP code, not the <? ?> shorthand.


  3. Use Space instead of Tabs. Use an indent of 4 spaces, with no tabs. This helps to avoid problems with diffs, patches, SVN history and annotations. Moreover Tabs behave differently in different places.

  4. Always write comments where ever possible, it helps your code to be more friendly for others and for you as well, when ever you read the code again. C style comments (/* */) and standard C++ comments (//) are both fine.
    /*
    Some comment will go here
    */

    // this is also a comment
  5. Use Meaningful, Consistent Naming Conventions. Naming this isn’t just for your own good. There’s nothing worse than trying to find your way through some other programmer’s nonsensical naming conventions. Help yourself and others by using names that make sense for your classes and functions.

  6. Don' create extra vaiables. Never define unnecessary variables. e.g
    // bad
    $description = strip_tags($_POST['description']); 
    echo $description;

    // good
    echo strip_tags($_POST['description']);
  7. Use UPPER case for the GLOBAL_CONSTANTS, and use "_" for word separators.

  8. Align the Declaration blocks for more readability. e.g.

    var       $mDate;
    var&      $mrDate;
    var&      $mrName;
    var       $mName;
    
    $mDate    = 0;
    $mrDate   = NULL;
    $mrName   = 0;
    $mName    = NULL;
  9. Always use the proper directory structure for placing the files. The structure can be any, but must be very handy and self descriptive. i.e Classes should be placed in classes folder only, similarly for the files containing functions in functions folder or what ever name you like. The core idea is always bunch the similar files in folders.

  10. Last but not the least, Always Turn on Error Reporting. Error reporting in PHP is very helpful. You’ll find bugs in your code that you might not have spotted earlier, as not all bugs keep the application from working. There are different levels of strictness in the reporting that you can use, but E_ALL will show you the most errors, critical and warnings alike.
 That's all for today. Thanks Guys.

23 comments: