PHP Standards and PSR Guidelines Overview

This document outlines various PHP standards, including PSR-1, PSR-2, PSR-3, PSR-4, PSR-5, PSR-6, PSR-7, focusing on coding standards, logging interfaces, autoloading, caching, and HTTP message interfaces.

Basic Coding Standards - PSR-1

PHP code files must start with <?php or <?= tags. They must be encoded in UTF-8 without BOM. Files should either declare classes, functions, constants, or perform side effects but not both simultaneously. Namespaces and class names must follow the PSR-4 auotloading standard. Class names use StudlyCaps, constants are uppercase with underscores, and method names follow camelCase.</p?>

File Structure

<?php
namespace Vendor\Model;

class Example {
    const VERSION = '1.0';
    public $exampleVar;
    public function exampleMethod() {
        // Method body
    }
}

Coding Style Guide - PSR-2

Code must adhere to PSR-1. Indentation uses 4 spaces. Lines should aim to stay under 80 characters but not exceed 120. A blank line follows namespace and use declarations. Classes and methods open braces appear on new lines.

Example Implementation

<?php
namespace Sample\Package;

use FirstInterface;
use SecondClass as SC;
use ThirdVendor\ThirdPackage\ThirdClass;

class Demo extends SC implements FirstInterface {
    protected static $property;
    
    public function sampleFunction($param) {
        if ($condition) {
            return true;
        } else {
            return false;
        }
    }
}

Logger Interface - PSR-3

Defines a LoggerInterface with methods for different log levels: debug, info, notice, warning, error, critical, alert, emergency. The log method accepts a level parameter that can be predefined or custom.

Logging Usage Example

function interpolate($message, array $context = []) {
    $replace = [];
    foreach ($context as $key => $val) {
        $replace['{' . $key . '}'] = $val;
    }
    return strtr($message, $replace);
}

$message = "User {username} created";
$context = ['username' => 'example'];
echo interpolate($message, $context);

Autoloading - PSR-4

Maps namespaces to directories. Each namespace corresponds to a directory base, and classes within the namespace correspond to files within those directories.

Sample Autoloader

<?php
spl_autoload_register(function ($className) {
    $prefix = 'MyProject\\';
    $baseDir = __DIR__ . '/src/';
    $len = strlen($prefix);
    if (strncmp($prefix, $className, $len) !== 0) {
        return;
    }
    $relativeClass = substr($className, $len);
    $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

Caching Interfaces - PSR-6

Standardizes cache handling through CacheItemPoolInterface and CacheItemInterface, supporting TTL, serialization, and immutable structures.

Cache Item Pool Interface

namespace Psr\Cache;

interface CacheItemPoolInterface {
    public function getItem($key);
    public function getItems(array $keys = []);
    public function hasItem($key);
    public function clear();
    public function deleteItem($key);
    public function deleteItems(array $keys);
    public function save(CacheItemInterface $item);
    public function saveDeferred(CacheItemInterface $item);
    public function commit();
}

HTTP Messages - PSR-7

Defines interfaces for HTTP messages, including requests and responses, stream handling, URI manipulation, and uploaded file management.

Request Interface Example

namespace Psr\Http\Message;

interface RequestInterface extends MessageInterface {
    public function getRequestTarget();
    public function withRequestTarget($requestTarget);
    public function getMethod();
    public function withMethod($method);
    public function getUri();
    public function withUri(UriInterface $uri, $preserveHost = false);
}

Tags: PSR-1 PSR-2 PSR-3 PSR-4 PSR-5

Posted on Thu, 29 Oct 2026 16:24:18 +0000 by Rippie