In modern PHP development, adhering to PHP FIG (PHP Framework Interop Group) PSR standards is essential for maintaining code quality and enhancing team collaboration. PSR2 focuses on coding style, while PSR4 defines autoloading rules. This article shares practical methods and examples for following these standards in team development.
PSR2 primarily concerns code style. Key requirements include:
class Example
{
public function foo()
{
if ($condition) {
// do something
} else {
// do something else
}
}
}Each line of code should not exceed 80 characters.
$example = 'This is a long example string that exceeds 80 characters';Use lowercase for keywords and namespaces, and leave one space between keywords.
namespace ExampleNamespace;
use ExampleSomeClass;
use ExampleAnotherClass;Use camelCase naming convention, with the first letter lowercase.
class Example
{
public function calculateResult()
{
// do something
}
}PSR4 focuses on class file organization and autoloading. The namespace should correspond to the file path. For example, a class with the namespace ExampleNamespace should be located at example/Namespace.php.
Use the namespace keyword to define namespaces and use the use keyword to reference classes from other namespaces.
Tools like Composer can automate class loading by specifying namespaces and directories in composer.json:
{
"autoload": {
"psr-4": {
"Example\": "src/"
}
}
}With this configuration, all classes starting with the Example namespace will automatically load from the src/ directory.
To ensure consistent coding standards, teams should establish a formal code review process. Every submission should pass the review to confirm adherence to PSR2 and PSR4 standards.
The PHP team development process following PSR2 and PSR4 standards includes:
Following these standards greatly improves code readability and maintainability, making team development more efficient and professional.