Introduction to PSR-12 in Laravel
Maintaining consistent code style across a Laravel project is essential for readability, maintainability, and team collaboration. The PHP Standard Recommendation 12 (PSR-12) provides a comprehensive set of coding style guidelines that have become the industry standard for modern PHP projects, including Laravel applications.
In this guide, we'll explore how to implement PSR-12 standards in your Laravel projects using two powerful tools: PHP-CS-Fixer for automatically fixing code style issues and PHP_CodeSniffer (PHPCS) for detecting violations. By the end, you'll have a robust setup that ensures your Laravel codebase remains clean and consistent.
Understanding PSR-12 Standards
PSR-12 is an extended coding style guide that builds upon PSR-1 (Basic Coding Standard) and PSR-2 (Coding Style Guide). It was accepted in August 2019 and addresses many aspects of PHP code formatting, including:
- Files must use only UTF-8 without BOM for PHP code
- Files should either declare symbols (classes, functions, constants) or cause side effects (generate output, change settings) but not both
- Namespace and class declarations follow specific structure rules
- Method and function declarations follow specific formatting rules
- Control structures have specific formatting requirements
- Consistent spacing and indentation rules
Here's a simple example of PSR-12 compliant Laravel controller method: