Current Location: Home> Latest Articles> In-Depth Understanding of PSR-2 and PSR-4 Standards: Keys to Enhancing PHP Team Collaboration

In-Depth Understanding of PSR-2 and PSR-4 Standards: Keys to Enhancing PHP Team Collaboration

M66 2025-07-28

Introduction

In multi-developer PHP projects, unified coding standards are essential for improving project efficiency and reducing maintenance costs. The PSR (PHP Standard Recommendations) proposed by PHP-FIG includes two widely adopted standards: PSR-2 and PSR-4. This article will explain the core requirements of these standards and illustrate their practical applications with examples.

Overview of PSR-2

PSR-2 is a coding style guide for PHP designed to enhance code readability and consistency within teams. Its main points include:

  • Use 4 spaces for indentation, disallowing tabs.
  • Use camelCase for variables, functions, and methods.
  • Use PascalCase for class names.
  • Keep each line under 80 characters, with a maximum of 120 characters.
  • Separate logical blocks with blank lines to improve clarity.

PSR-2 Coding Example


<?php

use FooBar;

class MyClass
{
    private $property;

    public function __construct()
    {
        $this->property = 'some value';
    }

    public function getProperty()
    {
        return $this->property;
    }
}

$myObject = new MyClass();
echo $myObject->getProperty();

Overview of PSR-4

PSR-4 focuses on autoloading and namespace organization. It uses Composer and a standardized directory structure to achieve automatic class loading, which is foundational in modern PHP development.

Key points include:

  • Organize code with namespaces that mirror the directory structure.
  • Use Composer to automate class loading, eliminating manual includes.

PSR-4 Directory Structure Example


├── src/
│   └── Foo/
│       └── Bar/
│           ├── Baz.php
│           └── Quux.php
└── vendor/
    └── autoload.php

Within this structure, the namespaces inside Baz.php and Quux.php should be:


namespace Foo\Bar;

Composer Configuration Example

To enable PSR-4 autoloading, add the following to composer.json:


{
    "autoload": {
        "psr-4": {
            "Foo\\Bar\\": "src/Foo/Bar/"
        }
    }
}

Then run this command to generate the autoload files:


composer dumpautoload

Conclusion

By following PSR-2 and PSR-4 standards, PHP development teams can greatly improve code consistency and maintainability. These standards not only make collaboration more efficient but also provide a solid foundation for long-term project evolution. It is recommended that teams adopt these standards to ensure clear code structure and standardized development workflows.

We hope the explanations and examples in this article help developers better understand and apply PSR-2 and PSR-4, thereby enhancing team collaboration efficiency.