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.
PSR-2 is a coding style guide for PHP designed to enhance code readability and consistency within teams. Its main points include:
<?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();
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:
├── 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;
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
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.