How to write modern PHP code?
Use Craft’s Coding Guidelines
When writing code, it is essential to adhere to the code style and conventions used for that particular project or company. At Republic, we have decided to follow Craft’s Coding Guidelines when developing within the Craft ecosystem.
Writing code according to PSR-12
The Craft CMS guidelines are based on PHP-FIG’s PSR-12 “Extended Coding Style Guide” standards which are written with the intention to
reduce cognitive friction when scanning code from different authors
which, to me, sounds lite a really good thing.
PHP code example written as PSR-12
There are no big surprises when it comes down to the code example, but it still gives us a fast overview of how code written in accordance with the standard looks like.
<?php
declare(strict_types=1);
namespace Vendor\Package;
use Vendor\Package\{ClassA as A, ClassB, ClassC as C};
use Vendor\Package\SomeNamespace\ClassD as D;
use function Vendor\Package\{functionA, functionB, functionC};
use const Vendor\Package\{ConstantA, ConstantB, ConstantC};
class Foo extends Bar implements FooInterface
{
public function sampleFunction(int $a, int $b = null): array
{
if ($a === $b) {
bar();
} elseif ($a > $b) {
$foo->bar($arg1);
} else {
BazClass::bar($arg2, $arg3);
}
}
final public static function bar()
{
// method body
}
}
Set up your editor to do the work
One way to reduce the cognitive load is to let the editor or IDE do most of the work for you. In PhpStorm you can have the IDE format and verify your code according to the Craft Coding Guidelines and have it format it when you save the file.
Download Craft CMS helpers
Craft CMS keeps a GitHub page with tools for PhpStorm.
Import the following specifications
- Craft_Code_Style.xml
Install via Preferences → Editor → Code Style → ⚙️ → Import Scheme… - Craft_Inspections.xml
Install via Preferences → Editor → Inspections → ⚙️ → Import Profile…
Install the following PhpStorm plugins
- Php Inspections (EA Extended) – Adds lots of PHP best practices inspections
- Yii2 Inspections – Adds some Yii 2 and Craft-specific inspections
Set up PhpStorm to auto format code
- Go to Preferences → Editor → Code Style and change Scheme to “Craft”
- Tick box for “Enable EditorConfig support” under General
- Tick box for “Turn formatter on/off with markers…” under Formatter
- Go to Preferences Tools → Action on Save → Reformat code
Make exceptions to the formatter
The @formatter:off and @formatter:on tags can be used to intentionally exclude a specifc part of the code from the formatter.
$i18n->translations[$id] = [
'class' => PhpMessageSource::class,
// @formatter:off
'sourceLanguage' => 'en-US',
'basePath'. => '@modules/hajommodule/translations',
'forceTranslation' => true,
'allowOverrides' => true,
// @formatter:on
];
This will keep the spacing around the => in the code above when formatting.
Automatically generated starter files
Another way is to let the system generat the boilerplate code used when developing. The code generated automatically adheres to the coding standard and gives you a head start.
Generate boilerplate files with Craft Generator
For Craft CMS 4+ you can install and use the new command line option craft make to scaffold new Craft CMS plugins, modules, and system components from the CLI.
I’d really like to nerd down into PSR-12!
Yes, so glad you asked. 😁
The PSR-12 “Extended Coding Style” requires adherence to PSR-1 “Basic Coding Standard” to ensure technical interoperability between files. This is primarily technical specifications such as file encoding, etc.
Overview of PSR-1 rules
- Files MUST use only
<?phpand<?=tags. - Files MUST use only UTF-8 without BOM for PHP code.
- Files SHOULD either declare symbols (classes, functions, constants, etc.) or cause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.
- Namespaces and classes MUST follow an "autoloading" PSR: [PSR-0, PSR-4].
- Class names MUST be declared in
StudlyCaps. - Class constants MUST be declared in all upper case with underscore separators.
- Method names MUST be declared in
camelCase.
PSR-12 also “extends, expands and replaces” **PSR-2: Coding Style Guide**, which was the first version of the coding style guide. It’s now deprecated in favor of PSR-12, but still sets most of the rules for writing PHP code according to the PHP-FIG guidelines.
Overview of PSR-2 rules
- Code MUST follow a "coding style guide" PSR [PSR-1].
- Code MUST use 4 spaces for indenting, not tabs.
- There MUST NOT be a hard limit on line length; the soft limit MUST be 120 characters; lines SHOULD be 80 characters or less.
- There MUST be one blank line after the
namespacedeclaration, and there MUST be one blank line after the block ofusedeclarations. - Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.
- Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.
- Visibility MUST be declared on all properties and methods;
abstractandfinalMUST be declared before the visibility;staticMUST be declared after the visibility. - Control structure keywords MUST have one space after them; method and function calls MUST NOT.
- Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.
- Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before.
… still not enough. I want more!
Clean Code
The repo Clean Code PHP has software engineering principles, from Robert C. Martin's book Clean Code, adapted for PHP.
This is not a style guide. It's a guide to producing readable, reusable, and refactorable software in PHP.
Not every principle herein has to be strictly followed, and even fewer will be universally agreed upon. These are guidelines and nothing more, but they are ones codified over many years of collective experience by the authors of Clean Code.
Inspired from clean-code-javascript.