4.5 Demonstrate ability to write code using Drupal Coding Standards

Review Drupal Coding Standards such as line spacing between @doc blocks. Review PHP constants.

A Review of some key Drupal.org Drupal Standards.

Indenting and Whitespace

  • Use an indent of 2 spaces, with no tabs.

  • Lines should have no trailing whitespace at the end.

  • One line space between namespace and use statements same with annotations and classes.

Annotations

Annotations are formatted docblocks that use PS4 to autoload classes into memory. In Drupal 8 they are used for plugin discovery metadata and configuration.

For example the TelephoneLinkFormatter in the core telephone field module annotation block

/**
 * Plugin implementation of the 'telephone_link' formatter.
 *
 * @FieldFormatter(
 *   id = "telephone_link",
 *   label = @Translation("Telephone link"),
 *   field_types = {
 *     "telephone"
 *   }
 * )
 */

Naming Conventions

Coding standards ensure that a team can cohesively work together on maintainable code. A few naming conventions to note are:

  • classes: UpperCamel Classes should not use underscores.

  • methods: lowerCamel

  • variables: $lowerCamelCase or $snake_case

  • PHP constants: always uppercase const CACHE_TEMPORARY = -1;

See more at on Drupal.org's Object-oriented code.

Other Resources

Last updated