0

PSR-12 — Extended Coding Style

Beginner5 min read·php-12-007
psr

Concept

PSR (PHP Standard Recommendation) is a series of standards published by the PHP-FIG (Framework Interoperability Group). PSRs enable libraries and frameworks to interoperate — a PSR-3 logger from Monolog can be used with Laravel, Symfony, or any other framework without modification.

Key PSR overview:

  • PSR-1: Basic coding standard — UTF-8, <?php tag, namespaces, class/method naming.
  • PSR-2: Coding style guide — deprecated in favor of PSR-12.
  • PSR-3: Logger interface — LoggerInterface with emergency/alert/critical/error/warning/notice/info/debug methods.
  • PSR-4: Autoloader standard (covered in php-12-004).
  • PSR-6: Cache interface — CacheItemPoolInterface and CacheItemInterface.
  • PSR-7: HTTP message interfaces — RequestInterface, ResponseInterface, StreamInterface, UriInterface. Foundation of most modern PHP HTTP clients.
  • PSR-11: Container interface — ContainerInterface with get() and has(). Enables swapping IoC containers.
  • PSR-12: Extended coding style guide — 4-space indent, opening braces on same line for methods, etc.
  • PSR-14: Event dispatcher interface.
  • PSR-15: HTTP server request handlers and middleware — RequestHandlerInterface, MiddlewareInterface.
  • PSR-16: Simple cache interface — simpler alternative to PSR-6.
  • PSR-17: HTTP factory interfaces.
  • PSR-18: HTTP client interface.

Code Example

php
<?php
// PSR-1: Basics
namespace MyApp\Services; // Must use namespaces
                           // File: src/Services/UserService.php

class UserService  // StudlyCaps class name
{
    public function getUserById(int $id): ?User  // camelCase method names
    {
        return null;
    }

    const VERSION = '1.0.0'; // SCREAMING_SNAKE_CASE constants
}

// PSR-12: Code style key rules
class ExampleClass extends BaseClass implements ContractOne, ContractTwo
{
    public function exampleMethod(
        string $first,
        string $second,
        ?string $third = null,
    ): string {
        if ($first === $second) {
            return $first;
        } elseif ($third !== null) {
            return $third;
        }

        return $first . $second;
    }
}
// Rules: 4-space indent, opening brace on same line for methods/classes
// that's on a line by itself only for control structures? No — PSR-12
// says method/class opening brace is on the SAME line.
// Control structure: opening brace on same line as statement.

// Checking PSR-12 compliance
// vendor/bin/phpcs --standard=PSR12 src/
// OR use Laravel Pint (opinionated formatter based on PSR-12)
// vendor/bin/pint