PHP Coding Standards
PHP Standards Recommendations (PSRs)
The primary coding standards for the PHP community are set by the PHP Framework Interop Group (PHP-FIG).
The main set of standards for PHP development are the PHP Standards Recommendations (PSRs).
All PHP development should aim to follow the PSRs as closely as possible.
The PSRs that apply most to day-to-day development work at CoLab are:
- PSR-1: Basic Coding Standard - standard coding elements that are required to ensure a high level of technical interoperability between shared PHP code.
- PSR-12: Extended Coding Style - extends the basic standards, and enumerates a shared set of rules and expectations about how to format PHP code.
- PSR-4: Autoloader - standard for autoloading of classes from file paths, and namespacing for classes.
- PSR-5: PHPDoc - standard for code documentation using inline comments.
- PSR-19: PHPDoc tags - list of the individual tags used for PHPDoc formatted comments.S
Implementing coding standards
To help implement the PSRs in your development, there are various tools you can use.
PHP_CodeSniffer (PHPCS) is a set of two PHP scripts; the main phpcs
script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf
script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent.
If using Composer for dependecy management (you really should), then you can add PHPCS to your dev dependencies:
composer require --dev squizlabs/php_codesniffer
PHPCS can be used via the CLI, or integrated with code editors, IDEs or build tooling. You can also set up pre-comit hooks in git to enforce coding standards.
Resources
- Article: Set Up PHP CodeSniffer for Local Development
- Guide: How to set up commit hooks for PHP
- Tutorial: What is a DocBlock? - phpDocumentor documentation.