Skip to content

Lesson 11 of 45 · Principles of Good Object Design

SOLID Principles Explained With Real Code

Intermediate•
lesson•
October 16, 2026•
~10 min read

The acronym everyone has heard

SOLID is a set of five object-oriented design principles that gets quoted often and misapplied often. You'll find it applied to codebases that didn't ask for any of it, in ways that produce more harm than good.

This lesson walks through the five principles, names what each one is doing, and says which ones earn their place in practical PHP work and which ones get applied where they shouldn't be.

What SOLID actually is

Robert Martin introduced these principles in a 2000 paper, "Design Principles and Design Patterns". Michael Feathers coined the SOLID acronym a few years later. Each letter stands for one principle:

  • S - Single Responsibility Principle

  • O - Open/Closed Principle

  • L - Liskov Substitution Principle

  • I - Interface Segregation Principle

  • D - Dependency Inversion Principle

Underneath the names, all five principles are about the same thing: keeping change manageable. They're different angles on "how do we organize code so that adding, modifying, or replacing behavior doesn't break everything around it?".

The principles are tools, not rules. Each one is right in some contexts and wrong in others.

S - Single Responsibility Principle

Martin's formulation, as it is usually quoted:

There should never be more than one reason for a class to change.

A frequent misreading is "a class should do one thing". That version sounds reasonable and falls apart immediately, because "one thing" is unbounded. A method does "one thing". A program does "one thing". The framing isn't useful for design decisions.

The actual version is sharper: a class should change for one reason. If billing rules change, the billing class changes. If validation rules change, the validation class changes. If the same class changes for both reasons, those are two responsibilities sharing a file, and they'll fight each other.

This is cohesion under another name. "Things that change together belong together; things that change for different reasons belong apart." That's SRP.

In practice:

PHP
<?php // Two reasons to change packed into one class. declare(strict_types=1); namespace App\Booking; use App\Billing\Currency; use App\Billing\Money; final readonly class GuestAccount { /** @param list<Money> $unpaidCharges */ public function __construct( private Guest $guest, private array $unpaidCharges, ) {} public function balanceDue(Currency $currency): Money { $total = Money::zero($currency); foreach ($this->unpaidCharges as $charge) { $total = $total->add($charge); } return $total; } public function exportPersonalData(): string { return json_encode([ 'guest_id' => $this->guest->id->value, 'email' => $this->guest->email()->value, ], JSON_THROW_ON_ERROR); } }

Guest is the class from the Immutable Objects lesson. balanceDue() follows billing rules: which charges count and how they add up. exportPersonalData() follows GDPR rules: which personal data a guest can ask for. If the billing rules change, this class changes. If the GDPR rules change, this class also changes. Pull them apart:

PHP
<?php declare(strict_types=1); namespace App\Billing; final readonly class GuestBalance { /** @param list<Money> $unpaidCharges */ public function __construct(private array $unpaidCharges) {} public function due(Currency $currency): Money { $total = Money::zero($currency); foreach ($this->unpaidCharges as $charge) { $total = $total->add($charge); } return $total; } }
PHP
<?php declare(strict_types=1); namespace App\Booking; final class GuestDataExport { public function export(Guest $guest): string { return json_encode([ 'guest_id' => $guest->id->value, 'email' => $guest->email()->value, ], JSON_THROW_ON_ERROR); } }

The billing rule now lives with the rest of billing, and a new GDPR requirement only touches GuestDataExport.

O - Open/Closed Principle

Bertrand Meyer coined the principle in Object-Oriented Software Construction (1988), where it meant extending a class by inheriting from it. Martin later recast it around interfaces and polymorphism, which is the version below. The usual one-line statement, shortened and not Martin's exact wording:

Software entities should be open for extension, but closed for modification.

The idea: when you need to add a new variant of behavior, you should be able to add it by writing new code, not by editing existing code.

In practice, this usually means programming against interfaces and using strategy or polymorphism for variation:

PHP
<?php declare(strict_types=1); namespace App\Pricing; use App\Billing\Money; use App\Reservations\DateRange; interface PriceCalculator { public function calculate(DateRange $stayDates, Money $nightlyRate): Money; }
PHP
<?php declare(strict_types=1); namespace App\Pricing; use App\Billing\Money; use App\Reservations\DateRange; final readonly class StandardPriceCalculator implements PriceCalculator { public function calculate(DateRange $stayDates, Money $nightlyRate): Money { return Money::fromCents( $nightlyRate->amountInCents * $stayDates->nights(), $nightlyRate->currency, ); } }
PHP
<?php declare(strict_types=1); namespace App\Pricing; use App\Billing\Money; use App\Reservations\DateRange; final readonly class WeekendPriceCalculator implements PriceCalculator { private const WEEKEND_SURCHARGE_PERCENT = 20; public function calculate(DateRange $stayDates, Money $nightlyRate): Money { $total = Money::zero($nightlyRate->currency); for ($night = $stayDates->checkIn; $night < $stayDates->checkOut; $night = $night->addDay()) { $cents = $night->isFriday() || $night->isSaturday() ? intdiv($nightlyRate->amountInCents * (100 + self::WEEKEND_SURCHARGE_PERCENT), 100) : $nightlyRate->amountInCents; $total = $total->add(Money::fromCents($cents, $nightlyRate->currency)); } return $total; } }

A PromoPriceCalculator that takes a discount percentage in its constructor follows the same shape. When a new pricing rule arrives, you write a new class that implements PriceCalculator. The existing classes don't change.

OCP is useful in narrow situations and badly cargo-culted in others. It earns its place when:

  • You have a stable abstraction with several variants that come and go.

  • Variants are added often.

  • The abstraction is genuinely polymorphic (each implementation handles the same kind of input and produces the same kind of output).

It doesn't earn its place when:

  • You have one implementation today and no plan for a second. Speculative open/closed is just over-engineering.

  • The "extension" is actually a different concept that needed a different shape.

  • The cost of the polymorphism is more than the cost of editing the original code in the rare case it changes.

L - Liskov Substitution Principle

Barbara Liskov introduced the idea in a 1987 keynote, and she and Jeannette Wing formalized it in 1994. This is the everyday paraphrase, not their wording:

Subtypes must be substitutable for their base types without altering the correctness of the program.

A simpler version: if you have a function that takes a base type, passing in any subtype should work without surprises. The subtype shouldn't suddenly throw exceptions the base type didn't, return different shapes than promised, or refuse to handle things the base type handled.

The classic example of an LSP violation is "a square is a rectangle". Mathematically, a square is a kind of rectangle (a rectangle whose width equals its height). In code, modeling Square extends Rectangle and overriding setWidth to also update the height breaks any code that thought it was working with a rectangle. The substitution surprises the caller.

LSP shows up in two places in real PHP code:

  • Inheritance: subclasses that override methods to do something the base class wouldn't do (throw, change return shape, alter side effects). This is one more reason to favor composition over inheritance.

  • Interfaces: implementations that pretend to follow a contract but quietly change behavior. An EventDispatcher::dispatch implementation that silently swallows exceptions, when the contract says exceptions propagate, is an LSP violation in interface form.

Here's a concrete case of the interface violation. A CancellationPolicy decides how much of a reservation's price gets refunded on cancellation (this is the same contract the Strategy Pattern lesson builds around):

PHP
<?php declare(strict_types=1); namespace App\Reservations\Cancellation; use App\Billing\Money; use App\Reservations\DateRange; use DateTimeImmutable; interface CancellationPolicy { public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money; }

A well-behaved implementation honors the contract. Whatever it's given, it returns a Money value. Never nothing, never an exception:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Cancellation; use App\Billing\Money; use App\Reservations\DateRange; use DateTimeImmutable; final readonly class NonRefundableCancellation implements CancellationPolicy { public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money { return Money::zero($totalPrice->currency); } }

Now the broken subtype. Reservations booked before the system tracked cancellation policies get routed to a LegacyCancellation, added later by someone patching a support ticket:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Cancellation; use App\Billing\Money; use App\Reservations\DateRange; use Carbon\CarbonImmutable; use DateTimeImmutable; use RuntimeException; final readonly class LegacyCancellation implements CancellationPolicy { public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money { if ($stayDates->checkIn->lessThan(CarbonImmutable::parse('2023-01-01'))) { throw new RuntimeException('No refund data for reservations this old.'); } return Money::zero($totalPrice->currency); } }

LegacyCancellation implements CancellationPolicy, so it type-checks everywhere the interface is expected. But any code that loops over reservations and calls refundFor now has to know, in advance, which implementation it received, or wrap every call in a try/catch that no other implementation needs. The contract said "return a refund amount." This implementation sometimes throws instead. Every caller written against the interface is now wrong for this one case, and nothing in the type system warned them.

The fix is one of two moves. Either make the contract itself honest about failure (refundFor documents a named exception that any implementation may throw, so every caller handles it), or admit that pre-2023 reservations aren't a CancellationPolicy variant at all and give them their own honest type instead of forcing them into the interface. The Null Object Pattern lesson shows a related legacy case, where a NullCancellationPolicy implements the interface and honors the contract by returning zero.

In practice, you don't usually invoke LSP by name. You invoke it implicitly every time you say "this implementation breaks the contract". The principle gives that complaint a label.

I - Interface Segregation Principle

The usual paraphrase, not Martin's exact wording:

Clients should not be forced to depend on methods they do not use.

In practice: prefer many small, role-specific interfaces over one large, kitchen-sink interface.

A common smell: a Repository interface with twenty methods, where each consumer uses two or three of them. Implementing the interface forces implementations to provide all twenty. Mocking the interface in a test forces the test to set up methods it doesn't care about. Changing the interface ripples to every implementation, even ones that don't use the changed method.

The fix is to split the interface by client role:

PHP
<?php declare(strict_types=1); namespace App\Booking; interface ReadsGuests { public function withId(GuestId $id): Guest; public function withEmail(EmailAddress $email): ?Guest; }
PHP
<?php declare(strict_types=1); namespace App\Booking; interface WritesGuests { public function save(Guest $guest): void; }

A read-only consumer depends on ReadsGuests. A write-only job depends on WritesGuests. A class that needs both depends on both. The single concrete EloquentGuests class still implements both interfaces; consumers don't have to know that.

ISP is useful, especially for keeping tests honest and dependencies precise. The trap is splitting interfaces by method count instead of by role. Five interfaces with one method each, each used by exactly one consumer, is over-engineering with the principle as cover.

D - Dependency Inversion Principle

Martin's formulation (1996):

High level modules should not depend upon low level modules. Both should depend upon abstractions.

The second half says abstractions should not depend on details, and details should depend on abstractions.

Practically:

  • Your business code shouldn't depend on the framework's mailer; it should depend on a Mailer interface, and the framework's mailer should be one implementation behind that interface.

  • Your business code shouldn't depend on Eloquent; it should depend on a Reservations interface (a port), and EloquentReservations should be one implementation.

  • Your business code shouldn't depend on a third-party SDK; it should depend on a domain interface that abstracts what the SDK does.

Decoupling your code from the framework is DIP in narrative form. Ports and adapters are DIP at the architectural level: dependencies point inward, toward the abstractions.

In the codebases I've worked on, DIP is the most consequential of the five for long-lived products. Get it right and swapping an SDK or upgrading the framework touches the adapters, while the business code stays as it is. Get it wrong and everything is glued to the specific implementations you happened to start with.

It's also the most over-applied. Adding an interface in front of every concrete class, regardless of whether there's any reason to swap, is the over-engineering trap. The interface earns its place when there's a real reason for the abstraction: testability, multiple implementations, framework decoupling, domain clarity. "I might want to swap it someday" is not a reason. "I want to fake this in tests" usually is.

Which ones earn their place

  • SRP: Strongest. Useful daily. Misread often, but the right reading is the most useful single principle in OO.

  • DIP: Strongest in long-lived codebases. The interface-everywhere trap is the misuse, but applied with judgment, it's the principle that buys the most for upgrade safety, testability, and framework decoupling.

  • OCP: Useful in narrow situations. Frequently over-applied. Reaching for it when a variation actually hurts is a better default than open-closed-everywhere.

  • ISP: Useful, especially for keeping test mocks small and dependencies precise.

  • LSP: Mostly a sanity check after the fact. Favoring composition removes most inheritance violations, but an interface implementation can still break its contract, as LegacyCancellation does. Worth knowing, rarely worth invoking by name.

The one thing to remember

SOLID works as a set of tools to reach for when something hurts. It goes wrong as a checklist to satisfy.

When you hear "this code violates SOLID", ask which letter, and ask what specifically would change if you fixed it. If the answer is "we'd add an interface" without a reason behind the interface, the principle isn't doing the work. If the answer is "we'd separate two reasons-to-change that are tangled together", the principle is doing exactly what it's for.

Course Content