BuiltByCactus

Engineering Handbook

Code Style

Tabs vs spaces

We use spaces at Built By Cactus.

Spaces allow us to set a maximum column width which makes diffs easier to read. For that reason alone spaces should be an easy choice.

Code style

When using PHP outside of WordPress, we should follow the PSR-1 and PSR-2 standards as closely as possible.

This makes our code easier to read and maintainable by other developers if needs be.

What does that mean?

In short, these are the main rules of PSR-1 and PSR-2.

PSR-1 is the basic coding standard for PHP and PSR-2 is the coding style guide. PSR-1 covers such requirements as:

PSR-2 covers such requirements as:

Enforcing styles

There are ways we can enforce this within our editor, for example:

PhpStorm

Editor config

If you don’t use PhpStorm, you may use a .editorconfig file to set these standards. Most IDEs and editors now support them. You can download a pre-set one from here

Linting

We can also lint our PHP to make sure it adheres to these guidelines. This can be done using some composer packages.1

Using composer we can call the PHP Codesniffer package. This can be installed as follows:

composer global require "squizlabs/php_codesniffer=*"

You can then use the command phpcs from the command line to format your code.

First we need to check what standards are installed, we can do this as follows:

phpcs -i

# The installed coding standards are MySource, PEAR, PSR1, PSR2, Squiz and Zend

We can then run this over our code like this:

phpcs --standard=PSR1,PSR2 /path/to/code/

We should then see a list of errors that need to be fixed along with their files and lines.

Automatically Fixing Errors

To automatically fix style errors we can use the PHP-CS-Fixer package.

To install it, run to following from the command line:

composer global require friendsofphp/php-cs-fixer

You can then use the command below to fix any errors. By default, the rules will fix to the PSR-1 and PSR-2 standards, but they can be overridden as per the documentation

php-cs-fixer fix /path/to/code