wiki:CodingStandard

Version 2 (modified by Pan Luo, 12 years ago) ( diff )

--

Coding Standard

Following coding standards is one of the easiest way for everybody to understand everybody's code.

Indenting and Whitespace

  • Never use tabulations in the code. Indentation is done by steps of 2 spaces:
<?php
class sfFoo 
{
  public function bar() {
    sfCoffee::make();
  }
}
  • Lines should have no trailing whitespace at the end.
  • Files should be formatted with \n as the line ending (Unix line endings), not \r\n (Windows line endings) or mac endings.
  • All text files should end in a single newline (\n). This avoids the verbose "\ No newline at end of file" patch warning and makes patches easier to read since it's clearer what is being changed when lines are added to the end of a file.
  • Don't put spaces after an opening parenthesis and before a closing one.
    <?php
    if ($myVar == getRequestValue($name))    // correct
    if ( $myVar == getRequestValue($name) )  // incorrect
    

Operators

  • All binary operators (operators that come between two values), such as +, -, =, !=, ==, >, etc. should have a space before and after the operator, for readability.
    <?php
    $foo = $bar; //correct 
    $foo=$bar;  //incorrect
    
  • Unary operators (operators that operate on only one value), such as ++, should not have a space between the operator and the variable or number they are operating on.
    <?php
    $i++;
    
  • When comparing a variable to a string, put the string first and use type testing when applicable:
    <?php
    if (1 === $variable)
    

Control Structures

  • Use braces for indicating control structure body regardless of number of statements it contains.
  • Control statements should have one space between the control keyword and opening parenthesis, to distinguish them from function calls.

For if statements:

<?php
if ($condition1 || $condition2) {
  action1;
} elseif ($condition3 && $condition4) {
  action2;
} else {
  defaultaction;
}

For switch statements:

<?php
switch ($condition) {
  case 1:
    action1;
    break;

  case 2:
    action2;
    break;

  default:
    defaultaction;
}

For do-while statements:

<?php
do {
  actions;
} while ($condition);

Function Calls

  • Functions should be called with no spaces between the function name, the opening parenthesis, and the first parameter; spaces between commas and each parameter, and no space between the last parameter, the closing parenthesis, and the semicolon. Here's an example:
    <?php
    $var = foo($bar, $baz, $quux);
    
  • Use camelCase, not underscores, for variable, function and method names:
    • Good: function makeCoffee()
    • Bad: function MakeCoffee()
    • Bad: function make_coffee()

Function Declarations

  • In a function body, return statements should have a blank line prior to it to increase readability.
    <?php
    function makeCoffee() 
    {
      if (false !== isSleeping() && false !== hasEnoughCaffeineForToday()) {
        canMakeCoffee();
    
        return 1;
      } else {
        cantMakeCoffee();
      }
    
      return null;
    }
    
  • Arguments with default values go at the end of the argument list. Always attempt to return a meaningful value from a function if one is appropriate.

Use underscores for option/argument/parameter names.

Class Constructor Calls

  • When calling class constructors with no arguments, always include parentheses:
    <?php
    $foo = new MyClassName();
    

Arrays

  • Arrays should be formatted with a space separating each element (after the comma), and spaces around the => key association operator, if applicable:
    <?php
    $some_array = array('hello', 'world', 'foo' => 'bar');
    
  • Note that if the line declaring an array spans longer than 80 characters (often the case with form and menu declarations), each element should be broken into its own line, and indented one level:
    <?php
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#size' => 60,
      '#maxlength' => 128,
      '#description' => t('The title of your node.'),
    );
    
  • Note the comma at the end of the last array element; This is not a typo! It helps prevent parsing errors if another element is placed at the end of the list later.

String Concatenations

  • Always use a space between the dot and the concatenated parts to improve readability.
  • Avoid evaluating variables within strings, instead opt for concatenation:
    <?php
    $string = 'something';
    $newString = "$string is awesome!";  // bad, not awesome
    $newString = $string.' is awesome!'; // better
    $newString = sprintf('%s is awesome', $string); // for exception messages and strings with a lot of substitutions
    
  • When using the concatenating assignment operator ('.='), use a space on each side as with the assignment operator:

Comments

All function and class methods should have their phpdoc own block:

  • All @... statements do not end with a dot.
  • @param lines state the type and the variable name. If the variable can have multiple types, then the mixed type must be used.
  • Ideally @... lines are vertically lined up (using spaces):
    <?php
    /**
     * Notifies all listeners of a given event.
     *
     * @param  Event  $event  A Event instance
     *
     * @return Event          The Event instance
     */
    public function notify($event)
    

All one line comments should be on their own lines and in this format:

<?php
// space first, with no full stop needed

PHP Code Tags

  • Don't end library files with the usual ?> closing tag. This is because it is not really needed, and because it can create problems in the output if you ever have white space after this tag.
  • Always use <?php ?> to delimit PHP code, not the shorthand, <? ?>.

Constants

Use lowercase PHP native typed constants: false, true and null. The same goes for array(). At the opposite, always use uppercase strings for user defined constants, like define('MY_CONSTANT', 'foo/bar'). Better, try to always use class constants:

<?php
class Coffee {
  const HAZ_SUGAR = true;
}
var_dump(Coffee::HAZ_SUGAR);

Tools

This documentation is based on Symfony Coding Standard and Drupal Coding Standard.

Note: See TracWiki for help on using the wiki.