php coding standard and tips

It is important that developers follow a certain coding standard to help make the code readable and maintainable. These are what I gathered so far as the best coding practice:

File formatting:
– Never close php tag when using zend framework, ie, “?>”
– Use 4 space indentation as tab spacing. It is possible to configure this in many IDE.
– Maximum line length should be within the programming space in the IDE. It should be around 80 to 120 chars. This helps clarity when reading the code.

Naming Conventions:
– Class names should contain only alphanumeric chars. Underscores are used as separators between directories. For example, Zend/Xyz/Abc.php maps to Zend_Xyz_Abc class.
– Interface classes must end with the word “interface”, eg Zend_Xyz_Interface
– Try to name files in one word, ie without space, underscores or hypen (even if they are allowed), eg “OrderDetails”
– PHP files should end with .php extension. Template files should end with .phtml or .tpl (for smarty).
– Functions, methods or variables should always be named in camelcase, starting with a lowercase letter, eg “camelCase”.
– functions, methods or variables which are declared protected or private should start with a single underscore. Try to use alpha chars only without underscore.
– Always use getters and setters as a good OOP practice.
– Constants should all be in uppercase, defined using the “const” contruct. Separate each word with an underscore, ie PRICE_PER_ORDER
– Do not use short tags, ie use echo instead.

Coding Style
– For long string, concatenate them with a space before the “.” operator, ie something like this:

$sql = "SELECT id, a , b, c from table"
          . "where name = 'blarblar'"
          . "order by id asc";

$test = array('a' => 'apple',
                   'b' => 'boy');

– When defining a class and function, use one true brace, ie the brace is underneath the name. When using if, else, foreach within a function or method, the brace is written on the same line and be indented by 4 spaces.
– All switch construct must have default case.
– All document blocks must be compatible with the phpdocumentor.
– All file that contains PHP code must have a header block that contains the following information:

/**
 * Short Desc
 *
 * Long Desc
 *
 * LICENSE: license information
 *
 * @version        $Id:$
 * @since           xxxxx
 * @author         xxxxx
 */

– Every method or function must have a docblock that contains the function desc, arguments and return values. If the function or method throws an exception, use the “@throw” tag.

Did I miss out anything?

Like it.? Share it:

Comments are closed.