PHP Code Style (PSR Standards)
In this page:
Introduction to PSR Standards
PSRs (PHP Standard Recommendations) are community-agreed conventions from the PHP-FIG group covering everything from code formatting to interfaces, letting independently written packages interoperate smoothly.
Example: Introduction to PSR Standards
<?php
echo "PSRs are community-agreed conventions from PHP-FIG for interoperability";
?>
Login to try C/C++/Java/PHP code in the editor
PSR-12 Code Style
PSR-12 defines exact rules for spacing, brace placement, and method signatures, so code from different developers or packages reads consistently instead of everyone following their own personal style.
Example: PSR-12 Code Style
<?php
class UserController
{
public function show(int $id): void
{
echo $id;
}
}
echo "Consistent spacing and brace placement, regardless of author";
?>
Login to try C/C++/Java/PHP code in the editor
PSR-4 Autoloading
PSR-4 standardizes how a namespace maps to a folder structure, which is the exact convention Composer's autoloader relies on to find and load classes without any manual configuration per package.
Example: PSR-4 Autoloading
<?php
// namespace App\Models; --> maps to src/Models/ per composer.json's psr-4 config
echo "Namespace structure mirrors folder structure";
?>
Login to try C/C++/Java/PHP code in the editor
PSR-3 Logger Interface
PSR-3 defines a standard logging interface (with methods like info(), warning(), error()), so a library can accept 'any PSR-3 logger' and work with Monolog, a custom logger, or anything else that implements it.
Example: PSR-3 Logger Interface
<?php
interface LoggerInterface {
function info($message);
function warning($message);
function error($message);
}
class SimpleLogger implements LoggerInterface {
function info($message) { echo "INFO: $message"; }
function warning($message) { echo "WARNING: $message"; }
function error($message) { echo "ERROR: $message"; }
}
(new SimpleLogger())->info("App started");
?>
Login to try C/C++/Java/PHP code in the editor
PSR-7 HTTP Messages
PSR-7 standardizes how HTTP requests and responses are represented as objects, which is what allows middleware from different packages to be composed together in frameworks that follow the standard.
Example: PSR-7 HTTP Messages
<?php
// interface RequestInterface { function getMethod(); function getUri(); }
echo "Standardizes HTTP requests/responses as objects across frameworks";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: