PSR-12 style
| File layout | |
| Spacing rules | |
| Before and after | |
| Enforce with PHPCS |
File layout
One PSR-12 file tells one story: opening tag, namespace, imports, then a single class. Side effects like connects and prints belong in bootstrap scripts, never next to class declarations.
namespace Shop; class Cart { private array $items = []; public function add(string $sku): void { $this->items[] = $sku; } }
Spacing rules
Braces always sit on their own lines for classes and methods, with one space after control keywords and around operators. Steady spacing turns diffs into one line changes instead of whole file rewrites.
if ($a === $b) { echo "equal\n"; } foreach ($items as $item) { echo $item . "\n"; }
Before and after
Compare a cramped signature with its PSR-12 twin: short lines, typed params, return type at the end. The logic is identical, yet the second version welcomes the next reader instead of testing them.
function total(float $price, float $tax): float { return $price + $tax; } $result = total(100.0, 20.0); echo $result . "\n";
Enforce with PHPCS
Humans forget spacing rules under deadline pressure, so let PHPCS check every file with the PSR-12 standard. Run the fixer locally, then add the same command to CI so style stays automatic.
vendor/bin/phpcs --standard=PSR12 src
FOUND 0 ERRORS IN 12 FILES
function fixed(string $name): string { return "hi " . $name; } echo fixed("Ada") . "\n";
Next: Strategy and factory
Article author: Arthur Isaev