Drupal Code standards - ben600324/wiki GitHub Wiki

Indenting and Whitespace

Use an indent of 2 spaces, with no tabs.

Operators

such as +, -, =, !=, ==, >, etc. should have a space before and after the operator

Casting

Put a space between the (type) and the $variable in a cast: (int) $mynumber

Control Structures

Control structures include if, for, while, switch, etc. Here is a sample if statement, since it is the most complicated of them: if (condition1 || condition2) { action1; } elseif (condition3 && condition4) { action2; } else { defaultaction; } (Note: Don't use "else if" -- always use elseif.) switch (condition) { case 1: action1; break;

case 2: action2; break;

default: defaultaction; } do { actions; } while ($condition);

Alternate control statement syntax for templates

In templates, the alternate control statement syntax using : instead of brackets is allowed. Note that there should not be a space between the closing parenthesis after the control keyword, and the colon, and HTML/PHP inside the control structure should be indented. For example: <?php if (!empty($item)): ?> <p><?php print $item; ?></p> <?php endif; ?>

<?php foreach ($items as $item): ?> <p><?php print $item; ?></p> <?php endforeach; ?>

Line length and wrapping

  • In general, all lines of code should not be longer than 80 characters.
  • Lines containing longer function names, function/class definitions, variable declarations, etc are allowed to exceed 80 characters.
  • Control structure conditions may exceed 80 characters, if they are simple to read and understand:

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: $var = foo($bar, $baz, $quux);

Function Declarations

Class Constructor Calls

Parameter and return typehinting

https://www.drupal.org/docs/develop/standards/coding-standards