28 8 / 2011

Codeigniter Coding Style Guide

File Format/Encoding: UTF-8, with no BOM

Line Endings: Unix LF

PHP Closing:

  Do no use ?>

  Use:
  /* End of myfile.php */ 
  /* Location: ./system/modules/mymodule/myfile.php */ 

Class and Method Naming

  eg: class Super_class
  eg: function get_properties()

  Class names starts with Uppercase. Class method all in lower case.
  Every word separated by underscores.

Variable Name

 eg: $table_id

 Lowercase and underscore separated.

Commenting

  /**
   * Super Class
   *
   * @param      Id
   * @type        Table type
   */
  class Super_class {

  /**
   * Get properties from table
   *
   * @param      properties string
   * @param      table name string
   * @return      string 
  function get_properties($pro, $table) 

  // single line comment
  $id = get_id();

  // multi line comments
  // will be separated from the block
  // with a blank space

  $id = get_id();

Constants

  eg: DOLLAR_SYMBOL

  Fully uppercase. User CI’ s constants when possible (can’t find the source).

TRUE, FALSE, and NULL

  Fully uppercase.

Logical Operators

  eg. if ( ! is_array($foo) && empty($foo))

  OR is preferred over || due to readability.
  && is fine. 
  A space before and after !

Comparing return values and Typecasting

  Use === and !== when possible

  eg. $str = (string) $var;
  Example of typecasting.

Database Table Names

  eg. exp_omg_table_col
  Prefix exp_ follow by personal prefix, then table name. CI will convert exp_ to 
  what is used as user’s installation.

One File per Class

Whitespace

  Use tab

Code Indenting

  eg.
  function foo()
  {
//
  }

  foreach ($arr as $key => $val) 
  {
//
  }  

  if ($foo === $bar)
  {
//
  } 
  single space after PHP control structure. That is the foreach and if statement above.

Private Methods and Variables

  eg. _time_ago();
  Should be prefix with underscore.

Strings

  eg: ‘This is a string’;
  “This is a string with {$var}” 

  A string is always single quoted unless you use variables in it, or to prevent
  escaping of quotes.

SQL Queries

  eg. $query = $this->db->query(‘SELECT something, something2,
         FROM a_table
         WHERE id = 1
         AND name = jon
     ’)

  Separate MYSQL keywords into different lines if they are long. Keywords are all
  uppercase.