Strategy Design Pattern in PHP and Laravel with Examples

Strategy Design Pattern in PHP and Laravel with Examples

What is the Strategy pattern?

The Strategy pattern is a behavioral design pattern. You define a family of algorithms, put each one in its own class behind a common interface, and make them interchangeable. The code that uses them (the context) doesn't care which one it gets. It just calls the interface.

In short: instead of one class deciding how to do something with a big if or switch, you hand it an object that already knows how.

Why use it?

I reach for Strategy when I see code like this growing over time:

public function calculate(string $type, float $amount): float
{
    if ($type === 'standard') {
        return $amount * 0.05;
    } elseif ($type === 'express') {
        return $amount * 0.1 + 5;
    } elseif ($type === 'free') {
        return 0;
    }

    throw new InvalidArgumentException('Unknown type');
}

Every new option means editing this method again. The benefits of switching to Strategy:

  • Open/closed principle: you add a new behavior by adding a class, not by editing existing code.
  • Smaller, focused classes: each strategy does one thing.
  • Easier testing: you test each strategy alone, and you can pass a fake strategy into the context.
  • Runtime choice: the behavior can be picked from config, user input or the database.

How to use it

  1. Define an interface that describes the behavior.
  2. Write one class per variation that implements the interface.
  3. Have the context class depend on the interface, not on a concrete class.
  4. Pick the concrete strategy somewhere else (a factory, config, or the container) and pass it in.

A plain PHP example

Let's rewrite the shipping calculation above.

interface ShippingStrategy
{
    public function cost(float $amount): float;
}

final class StandardShipping implements ShippingStrategy
{
    public function cost(float $amount): float
    {
        return $amount * 0.05;
    }
}

final class ExpressShipping implements ShippingStrategy
{
    public function cost(float $amount): float
    {
        return $amount * 0.1 + 5;
    }
}

final class FreeShipping implements ShippingStrategy
{
    public function cost(float $amount): float
    {
        return 0.0;
    }
}

The context only knows about the interface:

final class Checkout
{
    public function __construct(private ShippingStrategy $shipping) {}

    public function total(float $amount): float
    {
        return $amount + $this->shipping->cost($amount);
    }
}

$checkout = new Checkout(new ExpressShipping());
echo $checkout->total(100); // 115

To choose a strategy from a string, I keep a small map instead of an if chain:

$strategies = [
    'standard' => StandardShipping::class,
    'express'  => ExpressShipping::class,
    'free'     => FreeShipping::class,
];

$checkout = new Checkout(new $strategies[$type]());

Strategy in Laravel

Laravel's service container makes this pattern feel natural. Say you export reports in different formats.

namespace App\Exports;

interface ExportStrategy
{
    public function export(array $rows): string;
}

class CsvExport implements ExportStrategy
{
    public function export(array $rows): string
    {
        $out = fopen('php://temp', 'r+');
        foreach ($rows as $row) {
            fputcsv($out, $row);
        }
        rewind($out);

        return stream_get_contents($out);
    }
}

class JsonExport implements ExportStrategy
{
    public function export(array $rows): string
    {
        return json_encode($rows);
    }
}

Binding a default strategy

In a service provider, bind the interface to the implementation you want by default:

public function register(): void
{
    $this->app->bind(
        \App\Exports\ExportStrategy::class,
        \App\Exports\CsvExport::class
    );
}

Now any class that type-hints ExportStrategy gets the CSV version injected, and you can swap it in one place.

Choosing the strategy per request

When the user decides the format, resolve it at runtime:

class ReportController extends Controller
{
    private array $exporters = [
        'csv'  => CsvExport::class,
        'json' => JsonExport::class,
    ];

    public function download(Request $request)
    {
        $format = $request->validate([
            'format' => 'required|in:csv,json',
        ])['format'];

        /** @var ExportStrategy $exporter */
        $exporter = app($this->exporters[$format]);

        return response($exporter->export($this->rows()));
    }
}

Contextual binding

If different classes need different strategies, Laravel's contextual binding handles it without any conditionals:

$this->app->when(ApiReportService::class)
    ->needs(ExportStrategy::class)
    ->give(JsonExport::class);

You already use it in Laravel

Laravel itself relies on this idea. Cache stores, filesystem disks, mail transports and queue connections all share a common contract while the actual driver changes based on config. Switching from file to redis cache without touching your code is the Strategy pattern at work.

When not to use it

If you have two options that will never change, a simple if is fine. Strategy pays off when the number of variations grows, or when each variation has real logic worth testing on its own.

Tagged

No comments yet

Leave a comment

Security code

Comments are checked before they appear. See the privacy policy for how your data is used.