← Tilbage til koncepter

PSR Standards

PHP Standard Recommendations for code style og arkitektur

Kategori: Standards

🎯 Key Points

  • PSR-1: Basic Coding Standard - Fundamentale kodestandarder for PHP filer
  • PSR-12: Extended Coding Style - Detaljeret style guide for PHP kode formatering
  • PSR-4: Autoloading - Standard for autoloading classes baseret på namespace
  • PSR-7: HTTP Message Interfaces - Interfaces for HTTP requests og responses
  • PSR-11: Container Interface - Common interface for dependency injection containers
  • PSR-15: HTTP Server Request Handlers - Middleware og request handler interfaces
  • PSR-18: HTTP Client - Standard interface for HTTP client libraries
  • PSR-3: Logger Interface - Common logging interface (Psr\Log\LoggerInterface)
  • PSR-6: Caching Interface - Standard for cache libraries
  • PSR-16: Simple Cache - Simplified caching interface for common use cases

💻 Kode Eksempel

<?php

// PSR-4 Autoloading example
// composer.json configuration:
// "autoload": {
//   "psr-4": {
//     "Acme\\Blog\\": "src/"
//   }
// }

// PSR-3 Logger Interface Implementation
namespace Acme\Blog\Services;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

class FileLogger implements LoggerInterface {
    private string $logFile;
    
    public function __construct(string $logFile) {
        $this->logFile = $logFile;
    }
    
    public function log($level, $message, array $context = []): void {
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = !empty($context) ? json_encode($context) : '';
        $logMessage = "[{$timestamp}] {$level}: {$message} {$contextStr}" . PHP_EOL;
        file_put_contents($this->logFile, $logMessage, FILE_APPEND);
    }
    
    public function emergency($message, array $context = []): void {
        $this->log(LogLevel::EMERGENCY, $message, $context);
    }
    
    public function alert($message, array $context = []): void {
        $this->log(LogLevel::ALERT, $message, $context);
    }
    
    public function critical($message, array $context = []): void {
        $this->log(LogLevel::CRITICAL, $message, $context);
    }
    
    public function error($message, array $context = []): void {
        $this->log(LogLevel::ERROR, $message, $context);
    }
    
    public function warning($message, array $context = []): void {
        $this->log(LogLevel::WARNING, $message, $context);
    }
    
    public function notice($message, array $context = []): void {
        $this->log(LogLevel::NOTICE, $message, $context);
    }
    
    public function info($message, array $context = []): void {
        $this->log(LogLevel::INFO, $message, $context);
    }
    
    public function debug($message, array $context = []): void {
        $this->log(LogLevel::DEBUG, $message, $context);
    }
}

// PSR-12 Compliant code style
class UserController {
    public function __construct(
        private LoggerInterface $logger,
        private UserRepository $repository
    ) {}
    
    public function store(array $data): User {
        $this->logger->info('Creating new user', ['email' => $data['email']]);
        return $this->repository->create($data);
    }
}

💼 Hvornår bruges det?

  • Code style konsistens - Hold ensartet formatering på tværs af teams og projekter
  • Autoloading struktur - Implementer PSR-4 for automatisk class loading
  • HTTP abstraktion - Brug PSR-7 til framework-agnostic HTTP handling
  • Dependency injection - Implementer PSR-11 container interface for DI containers
  • Logging standardization - Brug PSR-3 så du kan skifte mellem logger implementations
  • Package development - Følg PSR standarder for at sikre bred kompatibilitet

⭐ Best Practices

  • Følg PSR-12 for code style - brug automated tools som PHP-CS-Fixer til at enforce standards
  • Implementer PSR-4 autoloading i alle projekter - det er industristandarden
  • Brug PSR interfaces i type hints frem for konkrete implementationer for bedre testbarhed
  • Konfigurer din IDE til at følge PSR-12 formatting automatisk
  • For libraries og packages, følg PSR standarder religiøst for maksimal kompatibilitet
  • Brug Composer's autoload standarder som følger PSR-4 out of the box
  • Document hvilke PSR standarder dit projekt følger i README filen
  • Run static analysis tools (PHPStan, Psalm) der checker PSR compliance

ℹ️ Quick Info

Kategori
Standards
Sværhedsgrad
Mellem