PHP — additional coding standards

Vishwa Chikate
2 min readFeb 17, 2022

--

Photo by Mohammad Rahmani on Unsplash

In this article i will mention few guidelines (default as well as additional curated by our team) which we always follow while writing a Class/Interface/Trait or any other OOP’s data structure in a Drupal or any PHP project. Components such as the name of the class, methods and the attributes, comments, documentation, sequence of the imports etc if written in a proper way can improve the whole readability of the code organisation wide.

I work on Drupal projects so will consider Drupal code as an example in most of the code snippets below.

The -: standard :-

The Drupal Coding Standards apply to code within Drupal and its contributed modules though not limited to PHP but also to the Javascript, CSS and the Twig code snippets (Coding standard on Drupal.org).

Normally we sniff our code against the PHP_CodeSniffer Drupal standard which is a great metric to check if the written code adheres to the defined Drupal Coding standards or not 😅.

Adding more to the List 🙊

We added few more rules, expected to be followed by every #developer/#reviewer in every phase of the SDLC. Taking few rules from PHP Mess Detector library this is what our extended rule set looks like.

Please note below list is completely opinionated and curated as per our own understanding of neatness 😆. Do consider this as a guideline and not a Standard.

1. Order of imports

Always start with imports from:

  • Custom written code/files
  • Drupal Core Classes as well the Symfony namespace.
  • Third party libraries added via composer.
  • Make sure they are arranged in ascending order.
Code snippet showing order of import statements

2. Avoid Switch case

The switch () case : is a useful expression which is used to evaluate some action based on the given condition, though being helpful we find it something which bloats the code, we end up adding multiple cases, code gets difficult to read.

With Drupal core and the Contributed modules moving towards becoming compatible with PHP 8.0, we should use features provided in the PHP ≥8.0 version. Check the new match expression provided in PHP 8.0.

Code showing match expression usage

3. Avoid use of Static class references

Cannot be injected hence should be avoided.

4. Order of Class methods

Member function written inside a class must be defined in ascending order of their function name. Improves readability 😌

Class methods ordered in ascending order of their names

5. MAX length of function

Something taken from PHP Mess Detector ruleset, but limit the max number of lines written inside a function.

I shall keep on adding additional rules to this article whenever we introduce a new or amend the existing one.

--

--