Composition and delegation

suggest change

Inheritance builds a class by extending another one: a CountingList is a TagList. Composition builds a class from other objects it holds in properties: a Notifier has a formatter and has a transport. Delegation is how a composed object gets work done: it forwards a call to one of the objects it holds, possibly doing something before or after.

"Favor composition over inheritance" is one of the oldest pieces of object-oriented advice. In PHP it is backed by language features: interfaces, constructor property promotion, readonly, first-class callables, traits, property hooks and lazy objects.

This article covers:

Related topics: Interfaces, Abstract Classes, Traits, Magic Methods, Dependency Injection and Immutability.

The fragile base class problem

Say you want a tag list that counts how many tags were ever added. Extending the existing class looks like the obvious solution:

<?php
class TagList
{
    protected array $tags = [];

    public function add(string $tag): void
    {
        $this->tags[] = $tag;
    }

    public function addAll(array $tags): void
    {
        foreach ($tags as $tag) {
            $this->add($tag);
        }
    }

    public function all(): array
    {
        return $this->tags;
    }
}

class CountingTagList extends TagList
{
    public int $added = 0;

    public function add(string $tag): void
    {
        $this->added++;
        parent::add($tag);
    }

    public function addAll(array $tags): void
    {
        $this->added += count($tags);
        parent::addAll($tags);
    }
}

$list = new CountingTagList();
$list->addAll(['php', 'oop', 'design']);
echo "tags:  ", count($list->all()), "\n";
echo "added: ", $list->added, "\n";

Output:

tags:  3
added: 6

The counter says 6 for 3 tags. TagList::addAll() happens to call $this->add() for each tag, and because add() is overridden, every tag is counted twice: once in addAll() and again in add().

Nothing in the public API of TagList tells you that addAll() uses add(). It's an implementation detail, and the subclass depends on it. If the author of TagList later changes addAll() to write to the array directly, the counter breaks in the other direction. A subclass depends on how its parent works, not just on what it promises. That is the fragile base class problem.

Composition: wrap instead of extend

The same feature built with composition: describe the API with an interface, keep the original class as a private field, and forward each call to it:

<?php
interface Tags
{
    public function add(string $tag): void;
    public function addAll(array $tags): void;
    public function all(): array;
}

final class TagList implements Tags
{
    private array $tags = [];

    public function add(string $tag): void
    {
        $this->tags[] = $tag;
    }

    public function addAll(array $tags): void
    {
        foreach ($tags as $tag) {
            $this->add($tag);
        }
    }

    public function all(): array
    {
        return $this->tags;
    }
}

final class CountingTags implements Tags
{
    public private(set) int $added = 0;

    public function __construct(private readonly Tags $inner) {}

    public function add(string $tag): void
    {
        $this->added++;
        $this->inner->add($tag);
    }

    public function addAll(array $tags): void
    {
        $this->added += count($tags);
        $this->inner->addAll($tags);
    }

    public function all(): array
    {
        return $this->inner->all();
    }
}

$list = new CountingTags(new TagList());
$list->addAll(['php', 'oop', 'design']);
$list->add('composition');
echo "tags:  ", count($list->all()), "\n";
echo "added: ", $list->added, "\n";

try {
    $list->added = 100;
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

Output:

tags:  4
added: 4
Cannot modify private(set) property CountingTags::$added from global scope

CountingTags only sees the public API of whatever it wraps, so how TagList::addAll() is implemented doesn't matter anymore. Some other things improved too:

The cost is boilerplate: all() does nothing but forward. We'll get rid of that later in this article.

Building objects from parts

Composition is also the default way to design new classes. Rather than a JsonEmailNotifier extends EmailNotifier extends Notifier hierarchy with one subclass for every combination, give Notifier the parts that vary:

<?php
interface Formatter
{
    public function format(string $subject, string $body): string;
}

interface Transport
{
    public function send(string $to, string $message): void;
}

final class PlainFormatter implements Formatter
{
    public function format(string $subject, string $body): string
    {
        return strtoupper($subject) . "\n" . $body;
    }
}

final class JsonFormatter implements Formatter
{
    public function format(string $subject, string $body): string
    {
        return json_encode(['subject' => $subject, 'body' => $body]);
    }
}

final class EchoTransport implements Transport
{
    public function send(string $to, string $message): void
    {
        echo "to {$to}:\n{$message}\n\n";
    }
}

final class Notifier
{
    public function __construct(
        private readonly Formatter $formatter,
        private readonly Transport $transport,
    ) {}

    public function notify(string $to, string $subject, string $body): void
    {
        $message = $this->formatter->format($subject, $body);
        $this->transport->send($to, $message);
    }
}

$transport = new EchoTransport();

$plain = new Notifier(new PlainFormatter(), $transport);
$plain->notify('alice@example.com', 'Welcome', 'Thanks for signing up.');

$json = new Notifier(new JsonFormatter(), $transport);
$json->notify('ops@example.com', 'Disk full', '/var is at 98%');

Output:

to alice@example.com:
WELCOME
Thanks for signing up.

to ops@example.com:
{"subject":"Disk full","body":"\/var is at 98%"}

With inheritance, 2 formats and 3 transports would take 6 subclasses. With composition it takes 5 small classes that can be combined in any way. Each one is easy to test on its own, and Notifier can be tested with fakes.

Constructor property promotion with private readonly is the idiomatic way to declare collaborators. The dependency can't be swapped out by accident after the object has been constructed.

Decorators: stacking behavior

A decorator implements an interface, wraps another implementation of the same interface and adds behavior around the calls it forwards. The caller can't tell the difference, so decorators can be stacked:

<?php
interface UserRepository
{
    public function find(int $id): ?array;
}

final class DbUserRepository implements UserRepository
{
    private array $rows = [
        1 => ['id' => 1, 'name' => 'Alice'],
        2 => ['id' => 2, 'name' => 'Bob'],
    ];

    public function find(int $id): ?array
    {
        echo "  [db] SELECT * FROM users WHERE id = {$id}\n";
        return $this->rows[$id] ?? null;
    }
}

final class CachingUserRepository implements UserRepository
{
    private array $cache = [];

    public function __construct(private readonly UserRepository $inner) {}

    public function find(int $id): ?array
    {
        if (!array_key_exists($id, $this->cache)) {
            $this->cache[$id] = $this->inner->find($id);
        }
        return $this->cache[$id];
    }
}

final class LoggingUserRepository implements UserRepository
{
    public function __construct(private readonly UserRepository $inner) {}

    public function find(int $id): ?array
    {
        $user = $this->inner->find($id);
        $result = $user === null ? 'null' : $user['name'];
        printf("  [log] find(%d) -> %s\n", $id, $result);
        return $user;
    }
}

$repo = new LoggingUserRepository(
    new CachingUserRepository(
        new DbUserRepository()
    )
);

foreach ([1, 2, 1, 3, 3] as $id) {
    echo "find($id)\n";
    $user = $repo->find($id);
    echo "  => ", $user['name'] ?? 'not found', "\n";
}

Output:

find(1)
  [db] SELECT * FROM users WHERE id = 1
  [log] find(1) -> Alice
  => Alice
find(2)
  [db] SELECT * FROM users WHERE id = 2
  [log] find(2) -> Bob
  => Bob
find(1)
  [log] find(1) -> Alice
  => Alice
find(3)
  [db] SELECT * FROM users WHERE id = 3
  [log] find(3) -> null
  => not found
find(3)
  [log] find(3) -> null
  => not found

The order you wrap them in matters. Here logging is the outermost layer, so it sees every call, including the ones the cache answers. Swap the two wrappers and only cache misses would be logged.

Each decorator does one thing: caching, logging, retries, metrics, authorization. The database class doesn't know about any of it. Compare that with a CachingLoggingDbUserRepository subclass chain, where every combination needs its own class and removing one feature means changing the hierarchy.

Note how CachingUserRepository uses array_key_exists(), not isset(). That way it also caches "not found" results, which is why the second find(3) doesn't reach the database.

Strategies: swapping an algorithm

The Formatter in Notifier is a strategy: an object that the composing class delegates one decision to. When the strategy is a single function, an interface with one method is often overkill. Store a Closure instead:

<?php
final class PriceCalculator
{
    /** @var Closure(float): float */
    private Closure $discount;

    public function __construct(callable $discount)
    {
        $this->discount = $discount(...);
    }

    public function withDiscount(callable $discount): self
    {
        return new self($discount);
    }

    public function total(array $prices): float
    {
        $sum = array_sum($prices);
        return round(($this->discount)($sum), 2);
    }
}

final class Discounts
{
    public static function none(float $sum): float
    {
        return $sum;
    }

    public static function percent(float $p): Closure
    {
        return fn(float $sum): float => $sum * (1 - $p / 100);
    }
}

$cart = [19.99, 5.00, 75.50];

$calc = new PriceCalculator(Discounts::none(...));
echo $calc->total($cart), "\n";

echo $calc->withDiscount(Discounts::percent(10))->total($cart), "\n";

$over50 = fn(float $sum): float => $sum > 50 ? $sum - 15 : $sum;
echo $calc->withDiscount($over50)->total($cart), "\n";

Output:

100.49
90.44
85.49

Some details:

Use an interface when the strategy has several related methods, needs a name in your type signatures, or carries its own state and configuration. Use a closure when it's a single function.

Automatic forwarding with __call

Writing one forwarding method per interface method is tedious. The magic method __call() runs whenever an inaccessible or nonexistent method is called, so a wrapper can forward everything generically:

<?php
final class Timed
{
    public array $timings = [];

    public function __construct(private readonly object $inner) {}

    public function __call(string $method, array $args): mixed
    {
        if (!method_exists($this->inner, $method)) {
            throw new BadMethodCallException(
                sprintf('%s::%s() does not exist', $this->inner::class, $method)
            );
        }
        $start = hrtime(true);
        try {
            return $this->inner->$method(...$args);
        } finally {
            $this->timings[$method][] = (hrtime(true) - $start) / 1e6;
        }
    }
}

final class Slugger
{
    public function slug(string $text, string $sep = '-'): string
    {
        $text = strtolower(trim($text));
        return trim(preg_replace('/[^a-z0-9]+/', $sep, $text), $sep);
    }
}

$s = new Timed(new Slugger());
echo $s->slug('Composition over Inheritance!'), "\n";
echo $s->slug(text: 'Hello World', sep: '_'), "\n";
echo count($s->timings['slug']), " calls timed\n";

try {
    $s->explode('x');
} catch (BadMethodCallException $e) {
    echo $e->getMessage(), "\n";
}

var_dump($s instanceof Slugger);

Output:

composition-over-inheritance
hello_world
2 calls timed
Slugger::explode() does not exist
bool(false)

Named arguments survive the trip: they arrive in $args as string keys, and ...$args passes them on as named arguments again.

This is handy for debugging tools, profilers and quick adapters, but it's a poor default:

Prefer explicit forwarding methods for anything that is part of your application's design.

Removing boilerplate with a trait

When you write several decorators for the same interface, put the forwarding in a trait once. Each decorator then overrides only the methods it cares about, because methods defined in the class take precedence over methods from a trait:

<?php
interface Cache
{
    public function get(string $key): mixed;
    public function set(string $key, mixed $value): void;
    public function has(string $key): bool;
    public function delete(string $key): void;
    public function clear(): void;
}

final class ArrayCache implements Cache
{
    private array $items = [];

    public function get(string $key): mixed { return $this->items[$key] ?? null; }
    public function set(string $key, mixed $value): void { $this->items[$key] = $value; }
    public function has(string $key): bool { return array_key_exists($key, $this->items); }
    public function delete(string $key): void { unset($this->items[$key]); }
    public function clear(): void { $this->items = []; }
}

/** Forwards every Cache method to $this->inner. */
trait ForwardsToCache
{
    private readonly Cache $inner;

    public function get(string $key): mixed { return $this->inner->get($key); }
    public function set(string $key, mixed $value): void { $this->inner->set($key, $value); }
    public function has(string $key): bool { return $this->inner->has($key); }
    public function delete(string $key): void { $this->inner->delete($key); }
    public function clear(): void { $this->inner->clear(); }
}

final class StatsCache implements Cache
{
    use ForwardsToCache;

    public private(set) int $hits = 0;
    public private(set) int $misses = 0;

    public function __construct(Cache $inner)
    {
        $this->inner = $inner;
    }

    public function get(string $key): mixed
    {
        if ($this->inner->has($key)) {
            $this->hits++;
        } else {
            $this->misses++;
        }
        return $this->inner->get($key);
    }
}

final class ReadOnlyCache implements Cache
{
    use ForwardsToCache;

    public function __construct(Cache $inner)
    {
        $this->inner = $inner;
    }

    public function set(string $key, mixed $value): void
    {
        throw new LogicException("cache is read-only, can't set '$key'");
    }
}

$store = new ArrayCache();
$stats = new StatsCache($store);
$stats->set('user:42', 'Alice');      // forwarded by the trait

echo $stats->get('user:42'), "
";
var_dump($stats->get('user:7'));
printf("hits=%d misses=%d
", $stats->hits, $stats->misses);

$ro = new ReadOnlyCache($store);
echo $ro->get('user:42'), "
";
try {
    $ro->set('x', 1);
} catch (LogicException $e) {
    echo $e->getMessage(), "
";
}

Output:

Alice
NULL
hits=1 misses=1
Alice
cache is read-only, can't set 'x'

StatsCache overrides get(), and ReadOnlyCache overrides set(). All other methods come from ForwardsToCache. The classes still implements Cache explicitly, so type checks and static analysis work. The trait has no interface of its own, but if it misses a method, PHP refuses to compile the class.

Notice what the trait is used for: it saves typing in classes that use composition. It isn't a replacement for composition. A trait's code is copied into the class at compile time, which makes it closer to inheritance than delegation: there is no separate object to swap out. See Traits for more.

Wrap collections, don't extend them

Extending ArrayObject or ArrayIterator to make a typed collection is tempting, but it gives your class the whole parent API, including methods that bypass your rules:

<?php
class Playlist extends ArrayObject
{
    public function add(string $song): void
    {
        $this->append($song);
    }
}

$p = new Playlist();
$p->add('So What');
$p->exchangeArray(['oops']);   // replaces everything
$p[] = 42;                     // not a string, accepted anyway
$p['x'] = new DateTime();      // arbitrary keys and values

print_r(array_map(get_debug_type(...), $p->getArrayCopy()));

Output:

Array
(
    [0] => string
    [1] => int
    [x] => DateTime
)

add() accepts only strings, but exchangeArray(), offsetSet() and append() are all public and accept anything. Instead, keep a private array and implement only the interfaces that you need, delegating to the array:

<?php
final class Playlist implements IteratorAggregate, Countable
{
    /** @var list<string> */
    private array $songs = [];

    public function add(string $song): void
    {
        $this->songs[] = $song;
    }

    public function getIterator(): Iterator
    {
        return new ArrayIterator($this->songs);
    }

    public function count(): int
    {
        return count($this->songs);
    }
}

$p = new Playlist();
$p->add('Blue in Green');
$p->add('So What');
$p->add('Freddie Freeloader');

foreach ($p as $i => $song) {
    echo "$i. $song\n";
}
echo count($p), " songs\n";
var_dump(method_exists($p, 'exchangeArray'));

Output:

0. Blue in Green
1. So What
2. Freddie Freeloader
3 songs
bool(false)

IteratorAggregate::getIterator() delegates iteration to an ArrayIterator (or to a generator with yield from $this->songs), and Countable makes count($p) work. The class has exactly the API you designed and no other methods.

Delegating properties with hooks

Before PHP 8.4, exposing a property of a composed object took a getter method or __get(). Property hooks let a property forward reads and writes directly, and interfaces can now declare properties:

<?php
interface HasName
{
    public string $name { get; }
}

final class Address
{
    public function __construct(
        public string $city,
        public string $country,
    ) {}
}

final class Person implements HasName
{
    public function __construct(
        public string $name,
        public Address $address,
    ) {}
}

final class Employee implements HasName
{
    public function __construct(
        private Person $person,
        public string $title,
    ) {}

    // delegated, read-write
    public string $name {
        get => $this->person->name;
        set { $this->person->name = $value; }
    }

    // delegated, read-only and computed
    public string $location {
        get => "{$this->person->address->city}, {$this->person->address->country}";
    }
}

function greet(HasName $who): string
{
    return "Hello, {$who->name}";
}

$person = new Person('Ada', new Address('London', 'UK'));
$emp = new Employee($person, 'Engineer');

echo greet($emp), "\n";
echo $emp->location, "\n";

$emp->name = 'Ada Lovelace';
echo $person->name, "\n";

try {
    $emp->location = 'Paris';
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

Output:

Hello, Ada
London, UK
Ada Lovelace
Property Employee::$location is read-only

This is the "law of Demeter" in practice: callers write $emp->location and don't reach through $emp->person->address->city, so Employee is free to change how it stores that data.

Lazy delegation with lazy proxies

Sometimes the expensive part of composition is creating the dependency: a database connection, a parsed configuration file, an HTTP client. PHP 8.4 can create a lazy proxy: an object that looks exactly like the real class and creates the real instance the first time its state is accessed, then delegates to it:

<?php
class ReportGenerator
{
    public function __construct(private string $dsn)
    {
        echo "  (connecting to {$dsn}...)\n";
    }

    public function monthly(string $month): string
    {
        return "report for {$month} from {$this->dsn}";
    }
}

final class ReportController
{
    public function __construct(private ReportGenerator $reports) {}

    public function handle(string $path): string
    {
        if ($path === '/health') {
            return 'ok';
        }
        return $this->reports->monthly('2026-10');
    }
}

$class = new ReflectionClass(ReportGenerator::class);
$reports = $class->newLazyProxy(
    fn(ReportGenerator $proxy) => new ReportGenerator('pgsql:host=db')
);

$controller = new ReportController($reports);
foreach (['/health', '/reports'] as $path) {
    echo "GET $path\n";
    $body = $controller->handle($path);
    echo "  -> $body\n";
    var_dump($class->isUninitializedLazyObject($reports));
}
var_dump($reports instanceof ReportGenerator);

Output:

GET /health
  -> ok
bool(true)
GET /reports
  (connecting to pgsql:host=db...)
  -> report for 2026-10 from pgsql:host=db
bool(false)
bool(true)

Dependency injection containers and ORMs use this kind of proxy for lazy services and lazy-loaded entities. In application code you rarely call it directly, but it's good to know what's happening.

When inheritance is the right choice

Composition isn't always better. Inheritance is fine when:

A rule of thumb: extend classes that were written to be extended, compose everything else. Make your own classes final by default. If someone needs different behavior, they can wrap your class behind its interface.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents