Lesson 9 of 45 · Principles of Good Object Design
Composition vs Inheritance
The hierarchy that grew teeth
You join a project. There's a class called BaseNotification. It has eleven abstract methods, six concrete ones, and a constructor that takes seven dependencies. You see it because somebody asked you to add a new kind of notification.
Below BaseNotification you find EmailNotification, SmsNotification, PushNotification, SlackNotification, and WebhookNotification. Below EmailNotification you find TransactionalEmailNotification and MarketingEmailNotification. Below MarketingEmailNotification you find RoomUpgradeOfferNotification, WinbackEmailNotification, and AbandonedBookingEmailNotification.
To add a new notification, you pick a parent. None of them quite fit. The closest one has a method you'd need to override and another method you'd need to suppress. You write your class anyway, comment out the method you don't need, override the one that almost works, and merge it. Then somebody refactors BaseNotification to add a twelfth abstract method. Every leaf class breaks. Half the team has Slack messages from CI.
This is the cost of using inheritance where composition would have been right. The classes know too much about each other. The structure is rigid in places that need to flex, and flexible in places that should have been locked.
The principle that catches this, before it gets out of hand, comes from the Gang of Four's Design Patterns (1994):
Favor object composition over class inheritance.
This lesson is about what each of those is, what each of them costs, and how to tell which one a problem in front of you actually wants.
What inheritance is, what it does
Inheritance says "this class is a kind of that class". EmailNotification extends BaseNotification declares that every email notification is, in some sense, a notification. The child gets the parent's methods and properties for free. The child can override methods. The child can add new ones.
What inheritance gives you:
Code reuse. Methods defined on the parent are usable on the child without rewriting them.
Polymorphism. A function that takes a
BaseNotificationcan receive any subclass and call the same methods on it.A vocabulary. The hierarchy expresses a relationship in the type system: this thing is that kind of thing.
What inheritance costs:
A permanent commitment to one classification. A class can extend exactly one parent (in PHP, Java, and C#). The relationship "a winback email is a marketing email" gets baked into the type system, and the only way to change it is to break every place that depended on the old shape.
Coupling between parent and child. The child can call protected methods on the parent. The child can override methods on the parent. Every change to the parent has to consider every child.
Implicit dependencies. When you read the child class, half its behavior lives in its parent. To understand what the child does, you have to read the parent. To understand what the parent does, you have to read the parent's parent. The chain compounds.
What composition is
Composition says "this class has a that". Notification doesn't extend Mailer; it has a Mailer. The mailer is a collaborator the notification uses, not a parent the notification inherits from.
What composition gives you:
Flexibility. The parts you compose into a class can be swapped at construction time. Tests can pass fakes. Different contexts can pass different implementations.
Explicit dependencies. The constructor signature lists what the class needs. There's no hidden behavior coming from a parent class.
No hierarchy lock-in. A class can compose with as many other classes as it needs. There's no "you can only extend one" limit.
Clearer change boundaries. If you change a collaborator, the things that compose with it have a clear contract (the interface) to be checked against. There's no inherited behavior to worry about silently breaking.
What composition costs:
A bit more wiring. You have to construct the collaborators and pass them in. The container handles most of this in modern PHP.
Less "free" code reuse. You don't automatically inherit a parent's helpers. You delegate to a collaborator instead.
For most things you'll model in a long-lived codebase, the wiring cost is real and small, and the inheritance costs are real and large.
A worked example
Let's take notification dispatch. Inheritance-first:
<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Booking\Guest;
use Illuminate\Contracts\Mail\Mailer;
abstract class BaseNotification
{
public function __construct(protected Mailer $mailer) {}
abstract public function send(Guest $guest, array $data): void;
abstract protected function template(): string;
protected function format(array $data): string
{
return implode(', ', $data);
}
protected function shouldSend(Guest $guest): bool
{
return $guest->acceptsNotifications();
}
}<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Booking\Guest;
use Illuminate\Mail\Message;
final class StayConfirmationNotification extends BaseNotification
{
public function send(Guest $guest, array $data): void
{
if (!$this->shouldSend($guest)) {
return;
}
$body = $this->format($data);
$this->mailer->send(
$this->template(),
['body' => $body],
fn (Message $message) => $message->to($guest->email()->value),
);
}
protected function template(): string
{
return 'stay-confirmation';
}
}That looks fine at first. Add a fifth, sixth, seventh notification, and the parent class collects ifs and overrides. Add SMS and the parent class either grows methods that don't apply to email, or splits, or grows another layer of abstract subclasses. Each addition leaves a small mark.
(Guest is the class from the Immutable Objects lesson, and the example assumes it also has an acceptsNotifications() method.)
Composition-first:
<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Booking\Guest;
final readonly class SendNotification
{
public function __construct(
private NotificationOptIn $optIn,
private Channel $channel,
private Template $template,
) {}
public function __invoke(Guest $guest, array $data): void
{
if (!$this->optIn->isAllowedFor($guest, $this->channel)) {
return;
}
$rendered = $this->template->render($data);
$this->channel->send($guest, $rendered);
}
}<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Booking\Guest;
interface Channel
{
public function send(Guest $guest, string $body): void;
}<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Booking\Guest;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Mail\Message;
final readonly class EmailChannel implements Channel
{
public function __construct(private Mailer $mailer) {}
public function send(Guest $guest, string $body): void
{
$this->mailer->raw(
$body,
fn (Message $message) => $message->to($guest->email()->value),
);
}
}SmsChannel and PushChannel follow the same shape. The other two collaborators (the opt-in check is reduced to the guest's single flag here, so it ignores the channel it receives):
<?php
declare(strict_types=1);
namespace App\Notifications;
use App\Booking\Guest;
final class NotificationOptIn
{
public function isAllowedFor(Guest $guest, Channel $channel): bool
{
return $guest->acceptsNotifications();
}
}<?php
declare(strict_types=1);
namespace App\Notifications;
interface Template
{
/** @param array<string, string> $data */
public function render(array $data): string;
}<?php
declare(strict_types=1);
namespace App\Notifications;
final readonly class StringTemplate implements Template
{
public function __construct(private string $pattern) {}
public function render(array $data): string
{
return strtr($this->pattern, $data);
}
}Now adding a sixth or seventh notification is just constructing SendNotification with a different Channel and Template, with no new subclass and no abstract method on a parent that can break everything.
The difference looks like more files at first. The variation moved out of the type system and into runtime composition.
When inheritance earns its place
Inheritance is the right call in a few cases:
True "is-a" relationships in the framework.
final class ReservationConfirmedEmail extends Mailable. The framework wants you to extendMailablebecause that's how it queues and renders your email. Fighting the framework here is more expensive than going along with it.Abstract base classes for genuine variation. A class hierarchy of
Commandtypes where the parent really does encode the protocol that all commands share, and the children only differ in their specific data, can be a clean fit for inheritance.Sealed hierarchies (in spirit). A small, stable, well-understood set of variants.
ReservationStatusmodeled as enum cases, or a small set of payment method classes that the codebase commits to maintaining together. PHP enums often fit this better than class inheritance.Single-level abstraction in tests. A
TestCasebase class that provides setup helpers is fine. The relationship is small, the parent is stable, and the alternative (composing a "test helpers" object into every test) is more verbose than the value justifies.
The pattern: inheritance is fine when the relationship is genuinely a kind-of relationship, the hierarchy is shallow (one or two levels at most), and the parent is stable.
The smell is when the hierarchy grows past two levels, when children start needing to override or skip parent behavior, or when "is-a" was a stretch in the first place ("is a marketing email a kind of email?" is closer to "has-a-channel that's email and a category that's marketing").
Extending package classes
It is very common that people also extend package classes and try to override their behavior via inheritance. I've seen a scenario where a health check package updated its base implementation, and when my team upgraded the package, the person who upgraded it didn't update our code accordingly. The health checks didn't work for a month or more until someone noticed.
Nothing failed during the upgrade. The subclass still loaded and the app still ran, so nothing pointed at the overrides. A subclass depends on how its parent works inside, and the package authors don't know your subclass exists. Mailable from the previous section is different: Laravel's own make:mail command generates a class that extends it, so its authors treat extending it as part of the contract.
Take a made-up package, Acme\Health. It ships a Check interface with one method, run(): Result, and a DatabaseCheck class that implements it by running a query against the default database connection. You want the check to query the reservations table, so you extend the class and override the protected method that returns the query:
<?php
declare(strict_types=1);
namespace App\Health;
use Acme\Health\Checks\DatabaseCheck;
final class ReservationsDatabaseCheck extends DatabaseCheck
{
protected function query(): string
{
return 'select 1 from reservations limit 1';
}
}Say the next major version of the package renames query() to probeQuery(). Your query() is now a method nobody calls. PHP raises no error, the check runs the package's default query, and it keeps reporting healthy even when the reservations table is missing.
When you need different behavior from a package class, try these first:
Use the extension point the package documents, if it has one: a config option, an interface you implement, an event you listen to.
Wrap the class instead of extending it. Compose it into your own class and call its public methods, which are the part a package's changelog usually covers.
If you do extend it, add a test that fails when the extended behavior stops working. For a health check, that's a test that breaks the exact thing your code checks and expects the check to report a failure. That test would have turned a month of silent failures into a red build on the upgrade pull request. Also mark every overriding method with PHP 8.3's
#[\Override]attribute: if the parent no longer has a method with that name, PHP stops with "has #[\Override] attribute, but no matching parent method exists" as soon as the class loads.
The wrapped version of the same check implements the package's Check interface, takes a DatabaseCheck in its constructor, and calls only its public run() method. (Result::ok(), Result::failed(), and $result->isFailure() belong to the made-up package too.)
<?php
declare(strict_types=1);
namespace App\Health;
use Acme\Health\Check;
use Acme\Health\Checks\DatabaseCheck;
use Acme\Health\Result;
use Illuminate\Database\ConnectionInterface;
use Throwable;
final readonly class ReservationsDatabaseCheck implements Check
{
public function __construct(
private DatabaseCheck $connectionCheck,
private ConnectionInterface $database,
) {}
public function run(): Result
{
$result = $this->connectionCheck->run();
if ($result->isFailure()) {
return $result;
}
try {
$this->database->select('select 1 from reservations limit 1');
} catch (Throwable $e) {
return Result::failed('Reservations table unreachable: ' . $e->getMessage());
}
return Result::ok();
}
}This class never touches the package's internals, so renaming a protected method can't break it. If the package changes run() or the Check interface, that's a change to its public API, which the changelog lists. It also fails loudly: PHP refuses to load a class whose run() no longer matches the interface it implements.
The test points the default connection at an empty in-memory SQLite database. The connection works, but the reservations table doesn't exist, so the check has to report a failure:
<?php
declare(strict_types=1);
namespace Tests\Feature\Health;
use App\Health\ReservationsDatabaseCheck;
use Tests\TestCase;
final class ReservationsDatabaseCheckTest extends TestCase
{
public function test_it_fails_when_the_reservations_table_is_missing(): void
{
config([
'database.connections.empty' => [
'driver' => 'sqlite',
'database' => ':memory:',
],
'database.default' => 'empty',
]);
$check = $this->app->make(ReservationsDatabaseCheck::class);
$this->assertTrue($check->run()->isFailure());
}
}It passes against both versions of ReservationsDatabaseCheck above. After the rename, the subclass fails it, because the package's default query succeeds on the empty database and the check reports healthy.
PHP-specific notes
final by default. Every class you write in this course's style is final unless you have a specific reason for it to be extensible. A class declared final can't be inherited from. That sounds restrictive; in practice, it forces you to use composition, and the codebase ages much better for it. The exceptions are framework base classes you genuinely need to extend.
Traits are not a way out. PHP traits are closer to copy-paste than to inheritance, but they bring the same problems: hidden behavior, implicit method resolution, hard-to-test interaction with the host class. Use traits sparingly. A useful house rule: ban custom traits, allowing only framework traits (HasFactory, RefreshDatabase) as exceptions. That rule is the practical version of "favor composition".
Abstract classes are inheritance with extra rules. They're inheritance you've committed to extending. They have all the costs above and the added cost that every child must implement every abstract method, even if it only needs part of the parent's behavior. Treat them the way you'd treat any inheritance: useful in narrow cases, dangerous as a default.
Interfaces aren't inheritance. An interface declares a contract. A class that implements it promises a shape and inherits no behavior. Interfaces compose freely and have none of the costs above. Implementing five interfaces is fine. Extending five classes is impossible (and would be a problem if it weren't).
Pitfalls
Composition explosion. I've seen "favor composition" turn into composing everything, even small classes that genuinely shared a stable parent. The codebase fills up with collaborators that only have one implementation, factories that build them, and constructor signatures with seven dependencies. That's its own kind of accidental complexity. Composition earns its place when the variation is real.
Delegation everywhere. A class that "composes" with another class but only forwards every method to it has just reinvented inheritance with extra steps. If your class is doing nothing but $this->thing->doX(), the composition is a smell of its own. The class either should be the thing, or it should genuinely add behavior on top of it.
Composing with concretes. Composition works best when you compose with interfaces (or abstractions you control). Composing with concrete classes pulls the costs of inheritance back in: you're now coupled to a specific implementation. The right shape is "this class needs something that does X", not "this class needs MailgunMailer".
Treating "favor" as "always". The cases above where inheritance fits exist for a reason. Don't rewrite a clean, two-level inheritance hierarchy into composition just to satisfy the principle. Only refactor when the inheritance is actually causing pain.
Why this principle keeps showing up
"Favor composition over inheritance" has been repeated for more than thirty years because inheritance gets reached for too easily.
In the codebases I've worked in, "is-a" relationships are rarer than they look. Most of the time, what looks like inheritance is actually two things: shared behavior (which composition handles cleanly) and a category label (which an enum, a tag, or an interface handles cleanly). When you decompose the apparent inheritance into those two things separately, the design usually gets simpler.
The one thing to remember
When you reach for extends, stop and ask: do I really need this class to be a kind of that class, or do I just need it to use some of its behavior? Usually the answer is the second one, and the right tool is composition. Save inheritance for the small number of relationships that are genuinely "is-a".
Related Links
- Replace Inheritance with Delegationrefactoring.guru's walkthrough of turning an "is-a" relationship into a "has-a" one, step by step.
- Replace Superclass with DelegateFowler's refactoring catalog entry for the same move, with a before-and-after sketch; the mechanics are in the book.
- TraitsThe PHP manual page on traits, the language feature that gives you method reuse without inheritance.
- Class AbstractionThe PHP manual page on abstract classes, useful for judging when a shared base class is actually justified.