Lesson 19 of 45 · Behavior and Variation
The Strategy Pattern
The if-else chain that keeps growing
You start with a simple refund calculation:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
final class RefundCalculator
{
public function refundFor(Reservation $reservation, DateTimeImmutable $now): Money
{
$daysBefore = (int) CarbonImmutable::instance($now)->diffInDays($reservation->stayDates->checkIn);
if ($reservation->cancellationPolicyType === CancellationPolicyType::Flexible) {
return $reservation->totalPrice;
}
if ($reservation->cancellationPolicyType === CancellationPolicyType::Moderate) {
return $daysBefore >= 5
? $reservation->totalPrice
: Money::zero($reservation->totalPrice->currency);
}
if ($reservation->cancellationPolicyType === CancellationPolicyType::Strict) {
return $daysBefore >= 14
? $reservation->totalPrice->applyDiscountPercent(50)
: Money::zero($reservation->totalPrice->currency);
}
return Money::zero($reservation->totalPrice->currency);
}
}Reservation here is trimmed to what this lesson needs: totalPrice, stayDates and cancellationPolicyType are public readonly properties, and cancellationPolicyType is nullable because some legacy reservations have none (the Null Object Pattern lesson handles that case). $daysBefore counts whole days, rounded down by the (int) cast. CancellationPolicyType is a backed enum with the cases Flexible, Moderate, Strict and NonRefundable:
<?php
declare(strict_types=1);
namespace App\Reservations;
enum CancellationPolicyType: string
{
case Flexible = 'flexible';
case Moderate = 'moderate';
case Strict = 'strict';
case NonRefundable = 'non_refundable';
}Then "long-stay" arrives with a different cutoff. Then "partner-tier" with per-night rules. Each addition is one more branch, and the branches start having sub-branches. Every change to one policy touches a method shared by all policies. Once partner-tier needs a rate table, the calculator needs it too, and every test for "moderate" cancellation has to build the calculator with a rate table it never reads.
This is the smell the Strategy Pattern fixes. Instead of one method that knows about all the variants, you have one interface and several implementations. Each variant lives in its own class.
What the Strategy Pattern is
The Strategy Pattern is a behavioral pattern where:
An interface defines a single algorithm or operation.
Multiple classes implement it, each with a different version of the algorithm.
The calling code holds the interface (not a specific implementation) and uses it without caring which version is wired in.
The choice of which implementation to use can be made at runtime, by configuration, or at construction time.
Sound like the Decorator Pattern? They share the "common interface, multiple implementations" shape. The difference is the goal:
A decorator wraps an inner object and adds behavior while preserving the contract.
A strategy replaces the algorithm. There's no "inner"; the strategy is the implementation.
A worked example
The cancellation policy, refactored into strategies:
<?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;
}<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Billing\Money;
use App\Reservations\DateRange;
use DateTimeImmutable;
final readonly class FlexibleCancellation implements CancellationPolicy
{
public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money
{
return $totalPrice;
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Billing\Money;
use App\Reservations\DateRange;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
final readonly class ModerateCancellation implements CancellationPolicy
{
public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money
{
return (int) CarbonImmutable::instance($now)->diffInDays($stayDates->checkIn) >= 5
? $totalPrice
: Money::zero($totalPrice->currency);
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Billing\Money;
use App\Reservations\DateRange;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
final readonly class StrictCancellation implements CancellationPolicy
{
public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money
{
return (int) CarbonImmutable::instance($now)->diffInDays($stayDates->checkIn) >= 14
? $totalPrice->applyDiscountPercent(50)
: Money::zero($totalPrice->currency);
}
}<?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);
}
}Choosing the strategy at runtime
The strategies exist; now something has to pick the right one for each reservation. Three common shapes:
1. Inject the chosen one directly.
When the choice happens at boot time (the binding tells you which one to use), the consumer just receives the interface:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Reservations\Cancellation\CancellationPolicy;
use DateTimeImmutable;
final readonly class CalculateRefundForReservation
{
public function __construct(
private CancellationPolicy $policy,
) {}
public function __invoke(Reservation $reservation, DateTimeImmutable $now): Money
{
return $this->policy->refundFor($reservation->totalPrice, $reservation->stayDates, $now);
}
}The container binds CancellationPolicy to a specific class; in Laravel that's one bind() call in a service provider. This only fits when every booking uses the same policy. In this lesson each reservation carries its own policy type, so the next two shapes choose per reservation.
2. Use a factory to choose at runtime.
When the choice depends on the reservation itself, a factory selects the right strategy:
<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Reservations\CancellationPolicyType;
use App\Reservations\Reservation;
final readonly class CancellationPolicyFactory
{
public function __construct(
private FlexibleCancellation $flexible,
private ModerateCancellation $moderate,
private StrictCancellation $strict,
private NonRefundableCancellation $nonRefundable,
) {}
public function for(Reservation $reservation): CancellationPolicy
{
return match ($reservation->cancellationPolicyType) {
CancellationPolicyType::Flexible => $this->flexible,
CancellationPolicyType::Moderate => $this->moderate,
CancellationPolicyType::Strict => $this->strict,
CancellationPolicyType::NonRefundable => $this->nonRefundable,
};
}
}The match is still there, but it's small, in one place, and only does selection. Adding a new strategy is one new class, one enum case, one constructor parameter and one match arm. The match has no null arm, so a reservation without a policy type would throw an UnhandledMatchError; the Null Object Pattern lesson adds that arm.
A class with the factory injected as $policies asks it for the policy and uses it: $this->policies->for($reservation)->refundFor($reservation->totalPrice, $reservation->stayDates, $now).
3. Map by key.
When you'd rather register strategies in a list than add a constructor parameter for each one, key the map by the enum's value:
<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Reservations\CancellationPolicyType;
use OutOfBoundsException;
final readonly class CancellationPolicies
{
public function __construct(
/** @var array<string, CancellationPolicy> */
private array $policies,
) {}
public function for(CancellationPolicyType $type): CancellationPolicy
{
if (!isset($this->policies[$type->value])) {
throw new OutOfBoundsException("No cancellation policy registered for {$type->value}.");
}
return $this->policies[$type->value];
}
}The map is built at boot time, so adding a strategy is one enum case and one registration, with no constructor parameter, and selection is one array lookup.
Something still has to build that array. In Laravel, a service provider does it: a singleton(CancellationPolicies::class, ...) closure that calls $app->make() once per policy and keys each result by its enum value. Symfony can build the map for you with a service locator, a small container that holds a declared list of services and only creates the one you ask for (the Dependency Injection lesson covers why this scoped kind of lookup is fine):
<?php
declare(strict_types=1);
namespace App\Reservations\Cancellation;
use App\Reservations\CancellationPolicyType;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;
final readonly class CancellationPolicies
{
public function __construct(
#[AutowireLocator([
CancellationPolicyType::Flexible->value => FlexibleCancellation::class,
CancellationPolicyType::Moderate->value => ModerateCancellation::class,
CancellationPolicyType::Strict->value => StrictCancellation::class,
CancellationPolicyType::NonRefundable->value => NonRefundableCancellation::class,
])]
private ContainerInterface $policies,
) {}
public function for(CancellationPolicyType $type): CancellationPolicy
{
return $this->policies->get($type->value);
}
}Callers see the same for(CancellationPolicyType) method as the array version. An unregistered key now throws the container's NotFoundExceptionInterface instead of OutOfBoundsException. With four small, stateless policies, creating only one of them saves nothing. It pays off when each strategy has heavy dependencies of its own, such as an API client, and a request only ever needs one.
Why this beats if-else
Each variant tests in isolation. A test for
StrictCancellationconstructs the class on its own. It doesn't have to pretend the flexible, moderate, and non-refundable branches don't exist.New variants don't change existing strategies.
LongStayCancellationis a new class; the interface and the other strategies stay as they are. Open-closed for the strategies themselves.Each strategy has its own dependencies. Some need a rate table for partner tiers, others are pure calculations. With the if-else version, all those dependencies sat in one class, even when most calls didn't use them.
Reading the code is reading one strategy at a time. When you debug "why is moderate cancellation wrong?", you open
ModerateCancellation, not the refund calculator.
Strategy vs other patterns
vs simple polymorphism. Any time you have an interface with multiple implementations, you're using polymorphism. Strategy is polymorphism applied specifically to algorithm selection. The reason to call it out as a pattern is to recognize when an if-else chain wants to be one.
vs State Pattern. State uses the same shape but for objects whose behavior changes based on internal state, not external selection. A reservation that behaves differently as
ReservationStatus::Pending,ConfirmedorCheckedInis a State problem.vs Specification. Strategy picks one whole algorithm. Specification builds yes-or-no checks you can combine.
When Strategy earns its place
The pattern is right when:
You have two or more distinct ways of doing the same operation.
The choice between them is stable enough that each one deserves a class.
Each variant has its own logic, its own dependencies, or its own size that makes it want a home.
New variants are expected (or current variants change often).
It's wrong when:
There's one variant today and no real plan for a second. You're solving an imagined problem, the over-engineering trap.
The variants are trivially small (one line of math each), no new ones are coming, and a
matchover the input is clearer than five files.The variants share too much. If most of the logic is identical and only one line differs, you have one algorithm with a parameter.
PHP-specific notes
Use enums for the selection key. When you select strategies by name, PHP enums make the keys type-safe. CancellationPolicyType::Strict is better than the string "strict".
Don't over-inject strategies. A FlexibleCancellation that takes seven dependencies for a five-line calculation is a sign that the strategy is doing too much. Keep strategies focused on the variation.
Pitfalls
Hidden coupling between strategies. A common smell is two strategies that "kind of share" implementation through a shared base class, with protected methods on the base. Now changes to one strategy ripple through the base into the others. The Composition vs Inheritance lesson covers the alternative. Hoist the shared logic into a separate collaborator they both compose with, not into a parent class they both inherit from.
Strategy that turns into a switch in disguise. A strategy class that has a giant match inside it on the input is no better than the if-else it replaced. The point of strategies is that each class is one variant. If a strategy branches on the kind of thing again (a second policy type, a partner tier), the variant probably covers two or more strategies.
Picking the strategy in the wrong place. The selection logic should live in one place (factory, map, or container binding). If the selection is duplicated across three files, the copies will drift apart in subtle ways.
The one thing to remember
When you find an if-else chain branching on a "kind of thing" (cancellation policy, payment provider, notification channel, pricing tier), each branch wants to be a strategy. The branching itself shrinks to a single small selection step.
Related Links
- StrategyThe standard write-up of the Strategy pattern and when an if-else chain should become one.
- Strategy in PHPA PHP example swapping payment strategies at runtime.
- Enumerations (PHP Manual)The PHP manual page on enums, useful for the type-safe selection keys this lesson recommends.
- Symfony - Service Subscribers & LocatorsThe AutowireLocator attribute this lesson uses to build the strategy map, and why a locator only creates the services a class asks for.