DEV Community

Russell Jones
Russell Jones

Posted on • Originally published at jonesrussell.github.io on

PSR-12: Extended Coding Style Guide in PHP

PSR-12 extends PSR-1 and PSR-2 (now deprecated) to provide a comprehensive coding style guide for modern PHP. This standard ensures consistency across PHP code by defining specific formatting rules.

Key Style Rules

1. General Code Layout

  • Files MUST use Unix LF line endings.
  • Files MUST end with a single blank line.
  • The closing ?> tag MUST be omitted from files containing only PHP.
  • Lines SHOULD be 80 characters or less.
  • There MUST be one blank line after namespace declarations.
  • Opening braces MUST be on the same line as the statement.

2. Class Structure

Here’s an example of a properly structured class:

<?php

declare(strict_types=1);

namespace Vendor\Package;

use Vendor\Package\SomeClass;
use Vendor\Package\AnotherClass as AClass;

class ClassName extends ParentClass implements \ArrayAccess, \Countable
{
    private const VERSION = '1.0';

    public function methodName(int $arg1, ?string $arg2): string
    {
        // method body
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Control Structures

Examples of control structures formatted according to PSR-12:

<?php

if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body
}

switch ($expr) {
    case 0:
        echo 'First case';
        break;
    default:
        echo 'Default case';
        break;
}

try {
    // try body
} catch (FirstThrowableType $e) {
    // catch body
} finally {
    // finally body
}

Enter fullscreen mode Exit fullscreen mode

Modern PHP Features

1. Type Declarations

Example of using type declarations in method signatures:

<?php

public function processUser(
    User $user,
    ?array $options = null
): ?Response {
    // Implementation
}

Enter fullscreen mode Exit fullscreen mode

2. Attribute Syntax

Example of using attribute syntax in PHP 8:

<?php

#[Route("/api/posts/{id}", methods: ["GET"])]
public function show(#[EntityId] int $id): Response
{
    // Implementation
}

Enter fullscreen mode Exit fullscreen mode

Tools for PSR-12 Compliance

  1. PHP_CodeSniffer Configuration
  2. PHP-CS-Fixer Setup
  3. IDE Integration
    • PhpStorm
    • VS Code with PHP Intelephense

Common Issues and Solutions

  1. Mixed Line Endings
# Check for mixed line endings
$ find . -name "*.php" -exec file {} \;

# Fix with dos2unix
$ find . -name "*.php" -exec dos2unix {} \;

Enter fullscreen mode Exit fullscreen mode
  1. Incorrect Indentation
// Bad
class Foo {
    function bar() {
return true;
    }
}

// Good
class Foo
{
    public function bar(): bool
    {
        return true;
    }
}

Enter fullscreen mode Exit fullscreen mode

Next Steps

In our next post, we’ll explore PSR-13, which defines standards for HTTP message interfaces in PHP. Check out our example repository for the implementation of these standards.

Resources

Example: Declare Statements

<?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;

Enter fullscreen mode Exit fullscreen mode

Example: Class Structure

<?php

namespace Vendor\Package;

class ClassName extends ParentClass implements \ArrayAccess, \Countable
{
    private $property;

    public function __construct()
    {
        // constructor body
    }
}

Enter fullscreen mode Exit fullscreen mode

Baamaapii 👋

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay