← Back to PHP Course | Chapter 16: Testing & Tools | Lesson 3 of 10

PHP Code Style (PSR Standards)

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
<?php
echo "PSRs are community-agreed conventions from PHP-FIG for interoperability";
?>

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
<?php
class UserController
{
    public function show(int $id): void
    {
        echo $id;
    }
}
echo "Consistent spacing and brace placement, regardless of author";
?>

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
<?php
// namespace App\Models; --> maps to src/Models/ per composer.json's psr-4 config
echo "Namespace structure mirrors folder structure";
?>

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
<?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");
?>

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
<?php
// interface RequestInterface { function getMethod(); function getUri(); }
echo "Standardizes HTTP requests/responses as objects across frameworks";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.