PHP Standard Recommendations (PSRs) are a collection of guidelines developed by the PHP Framework Interoperability Group (PHP-FIG). These standards ensure consistency, readability, and maintainability in PHP code across different projects and frameworks. In this article, we will explore the most important PSR standards and their practical implications.
1. PSR-1: Basic Coding Standards
PSR-1 lays down the foundational rules for PHP coding practices. It covers PHP tags, encoding, naming conventions, and class structure. The primary goal of PSR-1 is to ensure that code is interoperable between different frameworks and libraries.
Key Principles of PSR-1:
- Files must use only
<?php
and<?=
tags. - Files must use UTF-8 encoding without a BOM (Byte Order Mark).
- Class names must follow the PascalCase convention.
- Constants must be declared in all uppercase with underscores separating words.
- Method names must be declared in camelCase.
Example:
<?php
namespace App\Controllers;
class UserController
{
public function getUser($id)
{
return "User ID: " . $id;
}
}
Here, we use PascalCase
for the class name (UserController
) and camelCase
for method names (getUser
), which follow PSR-1 guidelines.
2. PSR-2: Coding Style Guide
PSR-2 builds on PSR-1 and provides a detailed coding style guide. It ensures that all PHP code is written in a consistent format, making it easier for developers to read and maintain the code.
Key Guidelines of PSR-2:
- Use 4 spaces for indentation, no tabs.
- The opening brace for classes and methods must be on the next line.
- Control structures like
if
,else
, andwhile
should have braces on the same line.
Example:
<?php
class Calculator
{
public function add($a, $b)
{
if ($a === 0) {
return $b;
} else {
return $a + $b;
}
}
}
Notice the 4-space indentation, and how the opening brace for the method appears on the next line, adhering to PSR-2 standards.
3. PSR-3: Logger Interface
PSR-3 standardizes a logging interface that allows developers to log messages in a consistent way. The advantage of PSR-3 is that it abstracts the logging logic, allowing developers to switch between different logging libraries without rewriting code.
Key Methods of PSR-3:
debug()
: Logs detailed debug information.info()
: Logs informational messages.notice()
: Logs normal but significant events.error()
: Logs runtime errors that do not require immediate action.
Example:
<?php
use Psr\Log\LoggerInterface;
class OrderController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function placeOrder($orderId)
{
$this->logger->info('Placing order with ID: ' . $orderId);
// Code to place the order
}
}
In this example, the logger is passed to the controller, allowing the info()
method to log the order placement.
4. PSR-4: Autoloading Standard
PSR-4 defines a way to automatically load classes from the file system, avoiding the need to manually include files. The file paths must map to namespaces, allowing easy loading of classes based on their names.
Key Rules of PSR-4:
- Namespace prefixes must match the file directory structure.
- The class name must map to a file path relative to the namespace.
Example:
// Directory: src/Controllers/ProductController.php
namespace App\Controllers;
class ProductController
{
public function showProducts()
{
echo "Showing products";
}
}
// In composer.json:
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
This PSR-4 autoloads the ProductController
class when it is called, mapping the App\Controllers
namespace to the src/Controllers/
directory.
5. PSR-7: HTTP Message Interface
PSR-7 defines common interfaces for working with HTTP requests and responses. It provides a consistent way to handle HTTP interactions between the client and the server, making it easier to integrate different libraries or frameworks.
Key PSR-7 Interfaces:
RequestInterface
: Handles the HTTP request.ResponseInterface
: Handles the HTTP response.
Example:
<?php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class ApiController
{
public function getResponse(ServerRequestInterface $request, ResponseInterface $response)
{
$response->getBody()->write('Hello, World!');
return $response;
}
}
In this example, PSR-7 handles the HTTP request and modifies the response body with a message.
6. PSR-12: Extended Coding Style Guide
PSR-12 expands on PSR-2, focusing on more modern PHP features and stricter coding practices, including typing, visibility declarations, and more.
Key Guidelines of PSR-12:
- Use
declare(strict_types=1);
to enforce strict typing. - All properties must have visibility declared (
public
,private
,protected
). - Split long class chains into multiple lines for better readability.
Example:
<?php
declare(strict_types=1);
class Order
{
private int $orderId;
private string $orderName;
public function __construct(int $orderId, string $orderName)
{
$this->orderId = $orderId;
$this->orderName = $orderName;
}
public function getOrderName(): string
{
return $this->orderName;
}
}
Here, we use strict_types
and declare visibility on all class properties, following PSR-12 guidelines.
Conclusion
PHP Standard Recommendations (PSRs) are essential for writing maintainable, scalable, and consistent PHP code. By adhering to these standards, you ensure that your code follows best practices and is easily interoperable with other frameworks and libraries. Whether you’re working on autoloading classes with PSR-4 or logging with PSR-3, these guidelines are indispensable for modern PHP development.
How to Create a QR Generator using HTML, CSS, and JavaScript