Skip to content

Lesson 18 of 45 · Behavior and Variation

The Decorator Pattern

Intermediate•
lesson•
October 27, 2026•
~8 min read

"Add logging to this, but don't touch it"

You have a payment gateway. It works. Production starts wanting an audit trail for every charge, refund, and authorization, and the team decides "let's log every call we make to the gateway".

The naive move is to open the gateway class and add logging inside the methods:

PHP
<?php declare(strict_types=1); namespace App\Payments; use App\Billing\Money; use App\Reservations\ReservationId; use Psr\Log\LoggerInterface; use Stripe\StripeClient; final class StripePayments { public function __construct( private StripeClient $stripe, private LoggerInterface $logger, ) {} public function authorize(ReservationId $id, Money $amount): PaymentAuthorization { $this->logger->info('payment.authorize.started', ['reservation' => $id->value, 'amount' => $amount->amountInCents]); $intent = $this->stripe->paymentIntents->create([ 'amount' => $amount->amountInCents, 'currency' => strtolower($amount->currency->isoCode), 'capture_method' => 'manual', 'metadata' => ['reservation_id' => $id->value], ]); $this->logger->info('payment.authorize.completed', ['payment_intent' => $intent->id]); return new PaymentAuthorization(new PaymentId($intent->id)); } }

Now the gateway has two jobs (talk to Stripe, write audit logs), and that pattern repeats across every method. Somebody adds metrics. The gateway has three jobs. Somebody else adds retries on transient errors. Four jobs. The class has lost its focus on actually being a payment gateway. It's a payment gateway plus three operational concerns, all woven together, all changing for different reasons.

The Decorator Pattern is the cleaner alternative. The logging, metrics, and retry behavior live in their own classes that wrap the gateway, each one adding its own behavior without modifying the underlying class.

What the Decorator Pattern is

The Decorator Pattern is a structural pattern where you wrap an object with another object that has the same interface. The wrapper adds behavior before, after, or around the original, while preserving the contract.

The shape:

  • An interface (the contract).

  • A concrete class implementing the interface (the inner object).

  • A decorator class that also implements the interface, holds the inner object as a property, and forwards calls to it, with extra behavior layered on.

From the outside, the decorator and the inner object are interchangeable. They both satisfy the interface. Anyone consuming the interface can be handed either one without noticing.

A worked example: logging

The interface is the contract. It uses result types in App\Payments that the lesson leaves out: PaymentId (the same shape as GuestId), and small readonly classes PaymentAuthorization (holding a PaymentId $id), PaymentCapture (holding the captured PaymentId $id) and PaymentRefund (holding the PaymentId $id and the refunded Money $amount). PaymentId also has a next() named constructor, which the fake in the Test Doubles lesson uses.

PHP
<?php declare(strict_types=1); namespace App\Payments; use App\Billing\Money; use App\Reservations\ReservationId; interface Payments { public function authorize(ReservationId $id, Money $amount): PaymentAuthorization; public function capture(PaymentId $id): PaymentCapture; public function refund(PaymentId $id, Money $amount): PaymentRefund; }

Payments is a port: the interface the business code owns. StripePayments is the adapter that implements it for Stripe.

PHP
<?php declare(strict_types=1); namespace App\Payments; use App\Billing\Money; use App\Reservations\ReservationId; use Stripe\StripeClient; final readonly class StripePayments implements Payments { public function __construct(private StripeClient $stripe) {} public function authorize(ReservationId $id, Money $amount): PaymentAuthorization { $intent = $this->stripe->paymentIntents->create([ 'amount' => $amount->amountInCents, 'currency' => strtolower($amount->currency->isoCode), 'capture_method' => 'manual', 'metadata' => ['reservation_id' => $id->value], ]); return new PaymentAuthorization(new PaymentId($intent->id)); } public function capture(PaymentId $id): PaymentCapture { $this->stripe->paymentIntents->capture($id->value, []); return new PaymentCapture($id); } public function refund(PaymentId $id, Money $amount): PaymentRefund { $this->stripe->refunds->create([ 'payment_intent' => $id->value, 'amount' => $amount->amountInCents, ]); return new PaymentRefund($id, $amount); } }

authorize is trimmed: Stripe can only capture an intent in the requires_capture state, so a real version also attaches a payment method and confirms the intent, which this lesson leaves out.

The decorator:

PHP
<?php declare(strict_types=1); namespace App\Payments; use App\Billing\Money; use App\Reservations\ReservationId; use Psr\Log\LoggerInterface; final readonly class LoggingPayments implements Payments { public function __construct( private Payments $inner, private LoggerInterface $logger, ) {} public function authorize(ReservationId $id, Money $amount): PaymentAuthorization { $this->logger->info('payment.authorize.requested', [ 'reservation' => $id->value, 'amount_cents' => $amount->amountInCents, ]); $auth = $this->inner->authorize($id, $amount); $this->logger->info('payment.authorize.completed', ['payment_intent' => $auth->id->value]); return $auth; } public function capture(PaymentId $id): PaymentCapture { $this->logger->info('payment.capture.requested', ['payment' => $id->value]); return $this->inner->capture($id); } public function refund(PaymentId $id, Money $amount): PaymentRefund { $this->logger->info('payment.refund.requested', [ 'payment' => $id->value, 'amount_cents' => $amount->amountInCents, ]); return $this->inner->refund($id, $amount); } }

The actual Stripe call still happens in StripePayments; the decorator only adds the logging around it.

Wiring decorators through the container

Symfony has a decorates option for this (see Related Links). In Laravel you bind the wrapped stack yourself:

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Payments\LoggingPayments; use App\Payments\Payments; use App\Payments\StripePayments; use Illuminate\Support\ServiceProvider; use Psr\Log\LoggerInterface; final class PaymentsServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(Payments::class, function ($app) { return new LoggingPayments( inner: $app->make(StripePayments::class), logger: $app->make(LoggerInterface::class), ); }); } }

Now anywhere that asks for Payments from the container gets LoggingPayments. The handlers don't change. The tests don't change (they bind their own implementation).

If you ever need to drop the logging for a feature, change the binding back. None of this requires touching StripePayments or any consumer.

Stacking decorators

The pattern shows its full value when you stack decorators. RetryingPayments and MetricsPayments follow the same shape as LoggingPayments and are omitted: each implements Payments, holds an inner Payments, and forwards every call. RetryingPayments takes a maxAttempts and repeats a call when the provider throws a transient error, and MetricsPayments records latency through a small Metrics interface.

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Payments\LoggingPayments; use App\Payments\Metrics; use App\Payments\MetricsPayments; use App\Payments\Payments; use App\Payments\RetryingPayments; use App\Payments\StripePayments; use Illuminate\Support\ServiceProvider; use Psr\Log\LoggerInterface; final class PaymentsServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(Payments::class, function ($app) { return new MetricsPayments( inner: new LoggingPayments( inner: new RetryingPayments( inner: $app->make(StripePayments::class), maxAttempts: 3, ), logger: $app->make(LoggerInterface::class), ), metrics: $app->make(Metrics::class), ); }); } }

Three concerns (retries, logging, metrics) are now three separate classes. The handler still asks for Payments. The order is a choice: retries sit innermost, so logging records one call however many attempts it took, and the metrics latency includes the retry time.

Retries need care on payment calls. Repeating authorize or refund after a timeout can charge or refund twice unless each call carries an idempotency key. Stripe accepts one on POST requests so that a retried request is not performed twice. The Payments interface has no place to pass a key, so StripePayments would have to derive a stable one per operation itself, and that derivation is left out here.

This is the principle of favoring composition over inheritance at work: instead of an inheritance tree of StripePayments → RetryingStripePayments → LoggedRetryingStripePayments, you have small, focused decorators that compose freely at runtime.

Why decorators win over modification

  • The original class stays focused. StripePayments does one thing: talk to Stripe. It's small, easy to test, easy to read.

  • The interface enforces honesty. Every decorator has to satisfy the same contract as the inner. A method added only on the decorator is unreachable, because consumers depend on the interface, not the decorator.

  • Open-closed in practice. New behavior arrives as a new decorator, and the inner class doesn't change. That's the Open/Closed Principle, applied with a wrapper instead of a new implementation.

When decorators earn their place

Decorators are the right tool when:

  • The behavior you're adding is cross-cutting. Caching, logging, metrics, retries, rate limiting, authorization, encryption, audit trails. These all wrap many operations the same way.

  • The behavior should be optional or configurable. You can disable retries by binding without the RetryingPayments wrapper. The capability turns on and off cleanly.

  • The behavior changes for different contexts. Per-tenant caching policies, per-environment logging levels, per-feature retry rules. Each context binds the stack it needs.

  • You're making a change you can't make to the inner class. The class is third-party. The class is generated. The class can't be modified for political or technical reasons. A decorator wraps it and adds what you need without touching it.

Decorators don't earn their place when:

  • The behavior you're adding is genuinely part of what the inner does. Writing a reservation and its rows in one transaction is the repository's own job, so it stays inside the repository.

  • The concern is one line in one place. A decorator adds a class and a container binding to save a single log call. That is over-engineering. Adding CachingGuests to a project with no performance problem is the same mistake.

  • The contract leaks. If your decorator needs to expose a method the interface doesn't have, the abstraction is breaking. Either widen the interface (for everyone) or rethink whether decoration is the right pattern here.

Pitfalls

A few common mistakes:

Decorating mutable state. A decorator that wraps an object whose state changes between method calls has to be very careful about what it caches, logs, or measures. The classic bug is a CachingReservations that keeps returning a reservation after another request cancelled it. When caching is the concern, the decorator also needs a rule for when an entry goes stale.

Leaky decorators. A decorator that exposes the inner object directly (getInner()) defeats the pattern. Consumers that call getInner() are reaching past the decoration to the raw object, which means the decorator can't be trusted to apply its behavior consistently.

Stacking too deep. Five decorators wrapping each other is fine in theory and a debugging headache in practice. When something goes wrong, you have to step through five layers to find which one did it. If you find yourself stacking more, ask whether some of the concerns belong together.

Decorators that aren't really decorators. A class that wraps another but exposes a different interface is an adapter or a facade. The interface contract is the part that makes the decorator transparent. Without it, you've just made the consumer's job harder.

The one thing to remember

When you find yourself wanting to add a cross-cutting concern (logging, metrics, retries, caching) to a class, the decorator pattern is usually the right tool.

Course Content