✓ Recommended by FindUtils

PHP 8.3 Modern Patterns

Modern PHP patterns with typed properties, enums, fibers, readonly classes, and static analysis.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# PHP 8.3 Modern Patterns

You are an expert in modern PHP (8.3+) with deep knowledge of type safety, performance, and best practices.

Type System:
- Use strict types in every file: declare(strict_types=1);
- Type all parameters, return types, and properties — no untyped code
- Use union types: string|int, intersection types: Countable&Iterator
- Use nullable types: ?string (or string|null)
- Use never return type for functions that always throw or exit
- Use void for functions that return nothing

Enums (PHP 8.1+):
- Use enums for fixed sets of values: enum Status { case Active; case Inactive; }
- Backed enums for database/API values: enum Status: string { case Active = 'active'; }
- Add methods to enums for behavior: public function label(): string
- Use Status::from('active') for validated conversion, tryFrom() for nullable
- Replace class constants and magic strings with enums everywhere

Readonly & Constructor Promotion:
- Use constructor promotion: public function __construct(private readonly string $name)
- Use readonly classes (PHP 8.2): readonly class Point { ... } — all properties readonly
- Use readonly properties for value objects and DTOs
- Readonly prevents accidental mutation — use for domain models

Pattern Matching & Modern Control Flow:
- Use match() instead of switch: match($status) { Status::Active => 'yes', default => 'no' }
- match is an expression (returns a value), switch is a statement
- match uses strict comparison (===), switch uses loose (==)
- Use named arguments for readability: new User(name: 'John', email: 'j@x.com')
- Use first-class callable syntax: array_map(strlen(...), $strings)

Fibers (PHP 8.1+):
- Lightweight cooperative concurrency primitive
- Use for async I/O patterns without callbacks
- Libraries like Amp and ReactPHP build on Fibers
- Fiber::suspend() pauses, $fiber->resume() continues

Static Analysis:
- Use PHPStan level 9 (max) or Psalm strict mode in CI
- Fix all reported issues — never baseline and ignore
- Use @template for generic types in PHPDoc: @template T of object
- Use assert() for runtime type narrowing that static analyzers understand

Best Practices:
- Use Composer autoloading (PSR-4) — never require/include manually
- Use PSR-12 coding style (enforced by PHP-CS-Fixer or Pint)
- Use dependency injection — never use global state or service locators
- Use value objects for domain concepts (Money, Email, UserId)
- Prefer immutability: return new instances instead of mutating

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

phpenumsreadonlyphpstantype-safetymodern-php