Home PHP PSR Standards and PHP-FIG: Writing Interoperable PHP
Intermediate 3 min · July 13, 2026

PSR Standards and PHP-FIG: Writing Interoperable PHP

Master PHP-FIG PSR standards to write interoperable, maintainable PHP code.

N
Naren Founder & Principal Engineer

20+ years shipping production PHP systems at scale. Lessons pulled from things that broke in production.

Follow
Production
production tested
July 13, 2026
last updated
2,073
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic knowledge of PHP syntax and OOP
  • Familiarity with Composer
  • PHP 7.4 or higher installed
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • PSR standards are PHP coding guidelines by PHP-FIG to ensure code interoperability.
  • Key standards: PSR-1 (basic coding), PSR-4 (autoloading), PSR-7 (HTTP messages), PSR-12 (extended coding style).
  • Adopting PSRs makes your code compatible with frameworks like Laravel and Symfony.
  • Use Composer for autoloading with PSR-4.
  • Tools like PHP_CodeSniffer enforce PSR-12 automatically.
✦ Definition~90s read
What is PSR Standards and PHP-FIG?

PSR standards are PHP coding guidelines created by PHP-FIG to ensure interoperability and consistency across PHP projects.

Think of PSR standards like traffic rules for PHP developers.
Plain-English First

Think of PSR standards like traffic rules for PHP developers. Just as traffic rules help cars drive safely together, PSR standards help different PHP libraries and frameworks work together without crashes. Following them means your code can easily plug into any PHP ecosystem.

Imagine you're building a PHP application that needs to send emails, handle payments, and generate PDFs. You find great libraries for each task, but they all have different coding styles, autoloading methods, and ways of handling HTTP requests. Integrating them becomes a nightmare of manual adjustments and compatibility hacks. This is exactly the problem the PHP Framework Interoperability Group (PHP-FIG) set out to solve with PSR (PHP Standards Recommendations) standards.

PHP-FIG is a group of PHP project representatives who collaborate to define common standards. By following PSRs, your code becomes predictable and interoperable with thousands of other PHP packages. Whether you're using a micro-framework or a full-stack CMS, PSR compliance ensures your code plays nicely with others.

In this tutorial, you'll learn the most important PSR standards: PSR-1 (basic coding standard), PSR-4 (autoloading), PSR-7 (HTTP message interfaces), and PSR-12 (extended coding style guide). We'll explore real-world examples, a production incident caused by ignoring PSR-4, and debugging techniques. By the end, you'll be able to write PHP code that any PSR-compliant project can consume.

What is PHP-FIG and Why PSR Standards Matter

PHP-FIG (PHP Framework Interoperability Group) is a collective of PHP project leaders who collaborate to create standards that promote interoperability. PSR (PHP Standards Recommendation) documents define these standards. Adopting PSRs ensures your code can work seamlessly with other PHP libraries and frameworks, reducing integration friction.

Key benefits
  • Interoperability: Your code can be used by any PSR-compliant project.
  • Maintainability: Consistent coding style makes code easier to read and maintain.
  • Tooling: Many tools (e.g., PHP_CodeSniffer, PHPStan) support PSRs out of the box.
  • Community: Following PSRs aligns you with best practices adopted by major projects like Laravel, Symfony, and Drupal.

Let's start with the foundational standards.

composer.jsonPHP
1
2
3
4
5
6
7
{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}
🔥PSR-0 vs PSR-4
📊 Production Insight
Always run composer dump-autoload after modifying autoload configuration.
🎯 Key Takeaway
PHP-FIG creates PSR standards to enable interoperability. Start with PSR-1 and PSR-4.

PSR-1: Basic Coding Standard

PSR-1 defines basic coding elements to ensure a high level of technical interoperability. Key rules: - Files MUST use only <?php and <?= tags. - Files MUST use UTF-8 without BOM. - Namespaces and classes MUST follow PSR-4 autoloading. - Class names MUST be declared in StudlyCaps. - Class constants MUST be declared in UPPER_CASE with underscores. - Method names MUST be declared in camelCase.

src/UserManager.phpPHP
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

namespace App;

class UserManager
{
    const MAX_LOGIN_ATTEMPTS = 5;

    public function getUserById(int $id): ?User
    {
        // implementation
    }
}
💡PSR-1 Compliance Check
🎯 Key Takeaway
PSR-1 provides a minimal set of rules for consistent PHP code.

PSR-4: Autoloading Standard

PSR-4 describes a specification for autoloading classes from file paths. It maps fully qualified class names to file paths based on namespace prefixes. This eliminates the need for manual require/include statements.

Key points
  • A namespace prefix (e.g., App\) maps to a base directory (e.g., src/).
  • Sub-namespaces correspond to subdirectories.
  • Class file names are case-sensitive and match the class name.
Example structure
  • Namespace: App\Library\Parser
  • File: src/Library/Parser.php
composer.jsonPHP
1
2
3
4
5
6
7
8
{
    "autoload": {
        "psr-4": {
            "App\\": "src/",
            "Monolog\\": "vendor/monolog/monolog/src/"
        }
    }
}
⚠ Common PSR-4 Mistake
📊 Production Insight
Always run composer dump-autoload -o for optimized autoloading in production.
🎯 Key Takeaway
PSR-4 maps namespaces to directories. Use Composer for autoloading.

PSR-7: HTTP Message Interfaces

PSR-7 standardizes HTTP messages (requests and responses) as objects. It defines interfaces for: - Psr\Http\Message\RequestInterface - Psr\Http\Message\ResponseInterface - Psr\Http\Message\ServerRequestInterface - Psr\Http\Message\StreamInterface - Psr\Http\Message\UriInterface

These interfaces allow frameworks and libraries to exchange HTTP data without coupling to specific implementations. For example, a middleware can modify a request object regardless of the underlying framework.

send-request.phpPHP
1
2
3
4
5
6
7
8
9
10
11
<?php

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

$client = new Client();
$request = new Request('GET', 'https://api.example.com/users');
$response = $client->send($request);

echo $response->getStatusCode(); // 200
echo $response->getBody(); // JSON body
Output
200
{"users": [...]}
🔥PSR-7 is Immutable
📊 Production Insight
Use PSR-7 compatible libraries (Guzzle, Symfony HTTP Client) to avoid vendor lock-in.
🎯 Key Takeaway
PSR-7 provides standard interfaces for HTTP messages, enabling framework interoperability.

PSR-12: Extended Coding Style Guide

PSR-12 extends PSR-2 (now deprecated) with modern PHP features. It covers: - Indentation: 4 spaces, no tabs. - Line length: soft limit 120 chars, hard limit 80 chars recommended. - Keywords: lowercase (true, false, null). - Braces: opening brace on same line for classes/methods, on new line for control structures. - Use declarations: one per line, alphabetically ordered. - Traits: one per line. - Anonymous classes: same as regular classes.

src/Example.phpPHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

declare(strict_types=1);

namespace App;

use App\Interface\SomeInterface;
use App\Trait\SomeTrait;

class Example implements SomeInterface
{
    use SomeTrait;

    public function doSomething(): void
    {
        if (true) {
            echo 'Hello';
        }
    }
}
💡Automate PSR-12
📊 Production Insight
Add PHP_CodeSniffer to your CI pipeline to prevent style violations from merging.
🎯 Key Takeaway
PSR-12 is the modern coding standard. Enforce it with automated tools.

Other Important PSRs

Beyond the core standards, several other PSRs address specific concerns: - PSR-3: Logger Interface – standardizes logging (e.g., Monolog implements it). - PSR-6: Caching Interface – defines cache pool and item interfaces. - PSR-11: Container Interface – standardizes dependency injection containers. - PSR-14: Event Dispatcher – standardizes event handling. - PSR-18: HTTP Client – defines a client interface for sending PSR-7 requests.

Adopting these PSRs makes your code compatible with a vast ecosystem of packages. For example, using PSR-3 allows you to swap logging libraries without changing your code.

logger-example.phpPHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php

use Psr\Log\LoggerInterface;

class UserService
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function registerUser(array $data): void
    {
        // ...
        $this->logger->info('User registered', ['email' => $data['email']]);
    }
}
🔥PSR-3 Logger
📊 Production Insight
Always depend on PSR interfaces rather than concrete implementations for flexibility.
🎯 Key Takeaway
Other PSRs like PSR-3, PSR-6, PSR-11 further enhance interoperability.
● Production incidentPOST-MORTEMseverity: high

The Autoloading Catastrophe: When PSR-4 Was Ignored

Symptom
After deploying a new feature, the site returned 500 errors for all pages. Logs showed 'Class not found' errors for a custom library.
Assumption
The developer assumed the new library would be autoloaded automatically because it was added to composer.json.
Root cause
The library's namespace did not match its directory structure (PSR-4 violation). Composer's autoloader could not find the classes.
Fix
Restructured the library's files to follow PSR-4: namespace App\Library\ mapped to src/Library/. Ran composer dump-autoload.
Key lesson
  • Always verify namespace-directory mapping matches PSR-4.
  • Use composer dump-autoload after adding new classes.
  • Test autoloading in a staging environment before production.
  • Include autoloading checks in your deployment pipeline.
  • Use tools like PHP_CodeSniffer to enforce PSR-4 compliance.
Production debug guideSymptom to Action3 entries
Symptom · 01
Class not found errors after deployment
Fix
Check composer autoload configuration and run composer dump-autoload.
Symptom · 02
Inconsistent coding style across team
Fix
Enforce PSR-12 with PHP_CodeSniffer in CI/CD pipeline.
Symptom · 03
HTTP message handling differs between libraries
Fix
Adopt PSR-7 interfaces for request/response objects.
★ Quick Debug Cheat SheetCommon PSR issues and immediate fixes
Class not found
Immediate action
Check namespace and directory structure
Commands
composer dump-autoload
php -r "require 'vendor/autoload.php'; echo 'OK';"
Fix now
Fix namespace in file or composer.json autoload mapping
Coding style violations+
Immediate action
Run PHP_CodeSniffer
Commands
vendor/bin/phpcs --standard=PSR12 src/
vendor/bin/phpcbf --standard=PSR12 src/
Fix now
Automatically fix with phpcbf
PSR-7 interface mismatch+
Immediate action
Check library versions
Commands
composer show psr/http-message
composer require psr/http-message:^1.0
Fix now
Update to compatible version
StandardFocusStatusExample
PSR-1Basic codingAcceptedClass names in StudlyCaps
PSR-4AutoloadingAcceptedNamespace to directory mapping
PSR-7HTTP messagesAcceptedRequest/Response interfaces
PSR-12Extended coding styleAcceptedBraces, indentation, use statements
⚙ Quick Reference
5 commands from this guide
FileCommand / CodePurpose
composer.json{What is PHP-FIG and Why PSR Standards Matter
srcUserManager.phpnamespace App;PSR-1
send-request.phpuse GuzzleHttp\Client;PSR-7
srcExample.phpdeclare(strict_types=1);PSR-12
logger-example.phpuse Psr\Log\LoggerInterface;Other Important PSRs

Key takeaways

1
PSR standards by PHP-FIG ensure code interoperability across the PHP ecosystem.
2
PSR-4 autoloading with Composer is essential for modern PHP development.
3
PSR-7 standardizes HTTP messages, enabling framework-agnostic middleware.
4
Enforce PSR-12 coding style with automated tools like PHP_CodeSniffer.
5
Adopt PSR interfaces (PSR-3, PSR-6, PSR-11) to decouple your code from specific implementations.

Common mistakes to avoid

3 patterns
×

Forgetting the trailing backslash in PSR-4 namespace prefix

×

Not running composer dump-autoload after adding new classes

×

Using PSR-0 style class names with underscores

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
What does PSR stand for and what is its purpose?
Q02SENIOR
Explain the difference between PSR-1 and PSR-12.
Q03SENIOR
How does PSR-4 autoloading work? Give an example.
Q01 of 03JUNIOR

What does PSR stand for and what is its purpose?

ANSWER
PSR stands for PHP Standards Recommendation. Its purpose is to promote interoperability between PHP projects by defining common coding standards, autoloading, and interfaces.
FAQ · 4 QUESTIONS

Frequently Asked Questions

01
What is the difference between PSR-0 and PSR-4?
02
How do I enforce PSR-12 in my project?
03
Can I use PSR-7 without a framework?
04
What is the latest PSR standard?
N
Naren Founder & Principal Engineer

20+ years shipping production PHP systems at scale. Lessons pulled from things that broke in production.

Follow
Verified
production tested
July 13, 2026
last updated
2,073
articles · all by Naren
🔥

That's Advanced PHP. Mark it forged?

3 min read · try the examples if you haven't

Previous
FrankenPHP and Modern PHP Runtimes
27 / 29 · Advanced PHP
Next
PHP Code Quality: PHPStan, Rector, Pint, and PHP CS Fixer