PHP Standards Recommendations (PSR) — A Comprehensive Guide

Roman Huliak
4 min read2 days ago

--

Photo by Ben Griffiths on Unsplash

Introduction

PHP Standards Recommendations (PSRs) are a set of standards that have played a crucial role in unifying the PHP community. These standards ensure consistency, interoperability, and best practices across PHP projects, frameworks, and libraries. The PHP-FIG (Framework Interoperability Group) is responsible for defining and maintaining PSRs.

This guide will explore the history of PSRs, their purpose, evolution over the years, current state, detailed explanations of key PSRs, examples of correct and incorrect implementations, and best practices.

Why Were PSRs Created?

Before PSRs, the PHP ecosystem was highly fragmented. Different frameworks and libraries had their own coding styles, autoloading mechanisms, logging systems, and HTTP message structures. This lack of consistency caused issues when integrating different PHP packages, leading to unnecessary complexity and incompatibility.

To solve these issues, PHP-FIG was formed by key members from major PHP projects like Symfony, Zend Framework, Laravel, and others. Their goal was to create a set of standards that the community could adopt to improve interoperability and maintainability.

PHP-FIG and the Evolution of PSRs

PHP-FIG introduced PSRs in a structured manner over the years. Initially, the focus was on coding standards and autoloading mechanisms. Later, more complex standards like HTTP messages, caching, and event dispatchers were introduced.

The Current State of PSRs

As of today, PHP-FIG continues to maintain and propose new PSRs. The standards are categorized as accepted, deprecated, or in draft status. Some of the most widely adopted PSRs include PSR-1 (Basic Coding Standard), PSR-4 (Autoloading Standard), PSR-7 (HTTP Message Interface), and PSR-12 (Extended Coding Style Guide).

Detailed Breakdown of Key PSRs

PSR-1: Basic Coding Standard

PSR-1 defines fundamental coding conventions that ensure code readability and interoperability. The key rules include:

  • PHP Tags: Only <?php and <?= should be used. The use of <? and <script language="php"> is not allowed.
  • Character Encoding: All PHP files must use UTF-8 encoding without a BOM.
  • Namespaces and Class Names: Class names must follow StudlyCaps naming convention. Namespace names should be in Vendor\Package format.
  • Method and Property Names: Method names should be written in camelCase.
  • Side Effects: A PHP file should either declare classes/functions/constants or execute logic, but not both.

Example of a PSR-1 Compliant Class

<?php
namespace MyProject\Utilities;

class DataProcessor
{
public function processData(array $data)
{
return array_map('strtoupper', $data);
}
}

PSR-4: Autoloading Standard

PSR-4 defines a standard for autoloading classes using namespaces, replacing the deprecated PSR-0. The key principles are:

  • Namespace prefix corresponds to a base directory.
  • Each class must be in its own file.
  • Class file paths must match namespace structure.

Correct PSR-4 Directory Structure

src/
MyProject/
Utilities/
DataProcessor.php

Example PSR-4 Class

<?php
namespace MyProject\Utilities;

class DataProcessor
{
public function processData(array $data)
{
return array_map('strtoupper', $data);
}
}

PSR-7: HTTP Message Interface

PSR-7 defines HTTP message interfaces for requests and responses, improving interoperability between different frameworks and libraries handling HTTP messages.

Example of PSR-7 Implementation with Guzzle

<?php
use GuzzleHttp\Psr7\Request;

$request = new Request('GET', 'https://example.com');
echo $request->getMethod(); // Outputs: GET

PSR-12: Extended Coding Style Guide

PSR-12 expands upon PSR-1 and PSR-2, providing a detailed guide for code formatting. Some key points include:

  • Line length should not exceed 120 characters.
  • Use spaces for indentation, not tabs.
  • Properties must have visibility declarations (public, protected, private).
  • No whitespace after the opening PHP tag.

Example of PSR-12 Compliant Code

<?php
namespace MyProject\Controllers;

use MyProject\Models\User;

class UserController
{
private User $user;

public function __construct(User $user)
{
$this->user = $user;
}
}

Common Mistakes to Avoid

Incorrect Autoloading

❌ Incorrect PSR-4 implementation:

namespace MyProject; // Should be MyProject\Utilities

class DataProcessor {}

Improper Naming Conventions

❌ Incorrect:

class data_processor {} // Class names must use StudlyCaps

✅ Correct:

class DataProcessor {}

Best Practices for PSR Compliance

  • Use a coding standard tool like PHP_CodeSniffer to enforce PSR rules.
  • Follow PSR-4 for autoloading to ensure compatibility with Composer.
  • Use PSR-3 (Logging) and PSR-7 (HTTP Messages) for better interoperability.
  • Review and update your codebase to align with PSR-12 for modern PHP practices.

Conclusion

PSRs have significantly improved the PHP ecosystem by standardizing coding practices, autoloading mechanisms, and HTTP message handling. By following these standards, PHP developers can create more maintainable, readable, and interoperable code.

Adopting PSRs in your projects ensures compatibility with widely used PHP frameworks and libraries. Whether you’re working on a small library or a large-scale application, adhering to these standards will make development smoother and collaboration easier.

By staying up-to-date with new PSRs and best practices, developers can continue contributing to a more unified PHP ecosystem.

--

--

Roman Huliak
Roman Huliak

Written by Roman Huliak

Full Stack Developer with 15 years of experience in ERP systems, skilled in leadership, analysis, and end-to-end development.

No responses yet