Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 147 ยท Modern PHP and Ecosystem

Coding Standards and PSRs

Write PHP that looks professional - PSR-1, PSR-12 and PER Coding Style rules, PSR-4 autoloading, the PSR-3/7/11/15 interfaces, and fixers like Pint and PHP-CS-Fixer.

Code is read far more often than it's written. When every file in a project follows the same layout, naming and spacing rules, you stop noticing the style and start seeing the logic. That's what a coding standard gives you: one agreed way to format code, so reviews discuss behavior instead of brace placement and any developer can open any file and feel at home.

PHP has an unusually strong shared standard. The PHP Framework Interop Group (PHP-FIG), a group of framework and library authors, publishes PSRs (PHP Standard Recommendations). Some PSRs are about style, some about autoloading, and many define small interfaces (for logging, HTTP messages, containers) that let libraries from different authors work together. This lesson covers the style rules you'll follow every day, the PSR-4 autoloading standard, the most important interface PSRs, and the tools that check and fix style automatically.

The style standards: PSR-1, PSR-12 and PER

Three documents define how modern PHP code looks:

  • PSR-1, Basic Coding Standard: the minimum rules every PHP file should follow: naming, file structure and side effects.
  • PSR-12, Extended Coding Style (2019): detailed formatting for PHP 7 syntax, replacing the older PSR-2.
  • PER Coding Style (PHP Evolving Recommendation): the successor to PSR-12. A PSR is frozen once accepted, so PHP-FIG created PER as a document it can keep updating as PHP gains new syntax such as enums, attributes, match and property hooks.

In practice, "follows PSR-12" and "follows PER" mean almost the same thing; new projects target PER. The rules you'll use most:

Topic Rule
Indentation 4 spaces, never tabs
Lines Unix line endings (\n); a soft limit of 120 characters; no trailing whitespace
Files <?php on the first line, no closing ?> in PHP-only files, end with one newline
Classes PascalCase names; opening brace { on its own line
Methods camelCase names; opening brace on its own line; visibility always declared
Control structures if, foreach, while: one space after the keyword, brace on the same line
Constants UPPER_SNAKE_CASE (MAX_RETRIES); enum cases are usually PascalCase
Keywords and types lowercase (true, null, int, array); short forms bool and int
Modifiers abstract/final first, then visibility, then static/readonly
Multi-line lists one item per line, with a trailing comma (PER)

Here's a class that follows those rules. Read it once for the layout rather than the logic:

PHP A PER-formatted class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the details: a blank line after <?php, after declare, after the namespace and after the use block; braces for the class and its methods on their own lines; the brace for if on the same line; constructor parameters one per line with a trailing comma; and ) { joining the multi-line parameter list to the constructor's body. The output is INV-2026-00001 and then INV-2026-00002.

A real project keeps one class per file and doesn't run code at the bottom of a class file. Our examples put a few lines of "usage" after the class so you can run them.

PSR-1: names and side effects

PSR-1 is short, and two of its rules matter beyond formatting.

Names. Classes, interfaces, traits and enums use PascalCase (PSR-1 calls it StudlyCaps), methods use camelCase, class constants use UPPER_SNAKE_CASE. Properties and variables have no official rule, but camelCase is by far the most common choice, and you should pick one style per project and stick to it. Every class lives in a namespace, at least one level deep (a vendor name like App or Acme).

Side effects. A file should either declare things (classes, functions, constants) or do things (print output, change settings, connect to a database), not both. A class file that also echoes something or calls ini_set() causes surprises the moment an autoloader includes it. That's why projects have a single entry point, such as public/index.php or bin/console, and every other file only declares code.

Checking style by machine

Humans are bad at spotting a stray tab or trailing space, and arguing about them in code review wastes everyone's time. Tools do it instead. To see how they work, here's a tiny checker built on PHP's own tokenizer. PhpToken::tokenize() splits source code into tokens exactly the way PHP's compiler does, so the checker understands code rather than guessing with regular expressions:

PHP A tiny style checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The checker finds six problems: the tab on line 4, the trailing spaces on line 5, the two badly named symbols, the missing visibility on the method, and the closing tag on line 7. Real tools check hundreds of rules this way, and most can also fix what they find, rewriting the tokens and saving the file.

The tools you'll actually use

All three of these are installed per project with Composer as development dependencies and run from the command line:

  • PHP-CS-Fixer fixes code to a rule set such as @PER-CS or @PSR12, configured in .php-cs-fixer.dist.php.
  • PHP_CodeSniffer has two commands: phpcs reports violations and phpcbf fixes the ones it can. Rules live in phpcs.xml. It's common in older and larger code bases.
  • Laravel Pint is a zero-configuration wrapper around PHP-CS-Fixer with presets (laravel, per, psr12), configured in pint.json. It works in any PHP project, not only Laravel ones.
Terminal
composer require --dev friendsofphp/php-cs-fixer
vendor/bin/php-cs-fixer fix --dry-run --diff   # show what would change
vendor/bin/php-cs-fixer fix                    # change the files

composer require --dev squizlabs/php_codesniffer
vendor/bin/phpcs --standard=PSR12 src/
vendor/bin/phpcbf --standard=PSR12 src/

composer require --dev laravel/pint
vendor/bin/pint --test                         # check only (for CI)
vendor/bin/pint                                # fix
PHP
<?php
// .php-cs-fixer.dist.php
$finder = PhpCsFixer\Finder::create()->in([__DIR__ . '/src', __DIR__ . '/tests']);

return (new PhpCsFixer\Config())
    ->setRules([
        '@PER-CS' => true,
        'declare_strict_types' => true,
        'ordered_imports' => true,
    ])
    ->setRiskyAllowed(true)
    ->setFinder($finder);

Run the fixer in your editor on save, and run it in check mode in CI (--dry-run or --test) so a pull request with badly formatted code fails automatically. Add an .editorconfig file too, so every editor uses 4 spaces and \n line endings before any tool runs. Style tools are different from static analysers like PHPStan and Psalm, which look for bugs rather than formatting; Testing PHP Code covers them.

When you adopt a fixer in an existing project, reformat the whole code base in one commit that changes nothing else. Mixing style changes into feature commits makes reviews and git blame painful.

PSR-4: where files live

PSR-4 is the autoloading standard. It maps a namespace prefix to a base directory, and the rest of the class name to subfolders and a file name. With the prefix App\ mapped to src/, the class App\Billing\InvoiceNumberGenerator must live in src/Billing/InvoiceNumberGenerator.php. Composer reads this mapping from composer.json and generates the autoloader (Autoloading and Composer covers the details):

JSON
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    }
}

The mapping is mechanical, which is the point: given a class name, any developer and any tool knows exactly which file to open. Here's the rule as a function:

PHP The PSR-4 mapping rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

File and folder names must match the class name exactly, including case. On Windows and macOS, src/billing/invoicenumbergenerator.php may load fine on your laptop, then fail on a Linux server where file names are case-sensitive.

The interface PSRs

Most PSRs aren't about style at all. They define small, shared interfaces, published as Composer packages under psr/..., so that code written against an interface works with any library that implements it. The ones you'll meet most:

PSR Defines Package Well-known implementations
PSR-3 Logger interface psr/log Monolog
PSR-6, PSR-16 Caching (pool / simple cache) psr/cache, psr/simple-cache Symfony Cache
PSR-7, PSR-17 HTTP messages and their factories psr/http-message Guzzle PSR-7, Nyholm, Laminas Diactoros
PSR-11 Container interface psr/container Symfony DI, PHP-DI, Laravel's container
PSR-14 Event dispatcher psr/event-dispatcher Symfony EventDispatcher
PSR-15 HTTP server middleware and handlers psr/http-server-middleware Slim, Mezzio
PSR-18 HTTP client psr/http-client Guzzle, Symfony HttpClient
PSR-20 Clock psr/clock Symfony Clock

The idea is easiest to see with PSR-3. Its LoggerInterface has methods for eight levels (emergency down to debug) plus a generic log(), and messages may contain filled from a context array. A library that accepts any LoggerInterface works with Monolog, a framework's logger or your own class. Without Composer we can't install psr/log, so this example declares a trimmed-down copy of the interface with three methods, but the shape is the same:

PHP Coding against a PSR-3 style logger

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PaymentService never mentions EchoLogger. Swap in Monolog writing to a file, or a test logger that records messages in an array, and the service doesn't change. That's the pattern behind all interface PSRs, and the basis of dependency injection (OOP Design Principles).

PSR-7 and PSR-15 do the same for web requests. PSR-7 represents a request and a response as immutable objects ($response->withHeader('Content-Type', 'application/json') returns a new response). PSR-15 defines a middleware, an object with one method, process($request, $handler), that can inspect or change the request, call the next handler, and inspect or change the response:

PHP
<?php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final class TimingMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $start = hrtime(true);
        $response = $handler->handle($request);          // call the rest of the app
        $ms = (hrtime(true) - $start) / 1e6;

        return $response->withHeader('Server-Timing', sprintf('app;dur=%.1f', $ms));
    }
}

A middleware written this way runs in any PSR-15 framework. Laravel and Symfony use their own request classes internally, but both offer bridges to PSR-7.

Documentation comments

Coding standards also cover comments. With typed parameters and return types, a docblock that repeats the signature adds nothing; write one when it adds information the types can't express: what an array contains, which exceptions are thrown, or why the code does something surprising. Static analysers read these annotations (The PHP Type System in Depth):

PHP
/**
 * Splits a cart into shipments of at most $maxWeight grams each.
 *
 * @param list<array{sku: string, grams: int}> $items
 * @return list<list<string>> SKUs per shipment
 * @throws InvalidArgumentException if one item is heavier than $maxWeight
 */
function planShipments(array $items, int $maxWeight): array
{
    // ...
}

The PHPDoc conventions (@param, @return, @throws, @var) were drafted as PSR-5 and PSR-19, which were never finalized, but every tool understands them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Following PSR-12 / PER, where does the opening brace go for a class, a method and an if statement?

    Classes, interfaces, traits, enums and methods put the opening brace on the next line. Control structures like if, foreach and while keep it on the same line.
  2. 2. With the PSR-4 mapping "App\\": "src/", which file must contain the class App\Mail\WelcomeMessage?

    The prefix App\ is replaced by src/, and the remaining namespace parts become folders. Case must match exactly, because Linux file systems are case-sensitive.
  3. 3. Why does PSR-1 say a file should declare symbols or cause side effects, but not both?

    Class files are included by the autoloader whenever a class is first used. If they also print or change settings, those effects happen at unpredictable moments.
  4. 4. What is the main benefit of a library depending on the PSR-3 LoggerInterface instead of a specific logger class?

    Interface PSRs let independently written libraries work together. The library only knows the interface, so the application chooses the implementation.
  5. 5. In CI, how should you run a fixer like Pint or PHP-CS-Fixer?

    Check mode reports violations with a non-zero exit code without changing files, so the pull request fails until the author runs the fixer locally.

Summary

  • PHP-FIG publishes PSRs. The style standards are PSR-1 (names, side effects), PSR-12 (formatting) and its maintained successor, PER Coding Style.
  • Key rules: 4 spaces, no closing ?> in PHP files, PascalCase classes, camelCase methods, UPPER_SNAKE_CASE constants, class and method braces on their own line, control-structure braces on the same line, declared visibility, trailing commas in multi-line lists.
  • Let tools enforce style: PHP-CS-Fixer, PHP_CodeSniffer (phpcs/phpcbf) or Laravel Pint, fixing in the editor and checking in CI.
  • PSR-4 maps a namespace prefix to a folder; the class name decides the exact file path, case included.
  • Interface PSRs (PSR-3 logging, PSR-7/17 HTTP messages, PSR-11 containers, PSR-15 middleware, PSR-18 HTTP clients, and more) let libraries from different authors work together.
  • Write docblocks when they add information the types can't express, such as array shapes and thrown exceptions.

Next: Testing PHP Code