SOLID Principles in Practice
Apply the five SOLID principles to real PHP classes.
Why SOLID
SOLID is five design principles that keep object-oriented PHP flexible, testable and resistant to rot. They are not rules to follow blindly but heuristics that reduce coupling and clarify responsibilities. In this lesson we apply each principle to concrete PHP classes you would actually ship.
- Single Responsibility
- Open/Closed
- Liskov Substitution
- Interface Segregation
- Dependency Inversion
Single Responsibility
A class should have one reason to change. A class that builds a report, formats it as HTML, and emails it has three reasons to change. Split persistence, formatting and transport.
Below, Invoice only models data; rendering and saving live elsewhere.
<?php
final class Invoice {
public function __construct(
public readonly string $number,
public readonly int $cents
) {}
public function total(): float { return $this->cents / 100; }
}
final class InvoiceRenderer {
public function toText(Invoice $i): string {
return sprintf('Invoice %s: $%.2f', $i->number, $i->total());
}
}
$i = new Invoice('INV-1', 12500);
echo (new InvoiceRenderer())->toText($i), PHP_EOL;