BehavioralPHPverifiedVerified

Strategy Pattern in PHP

Defines a family of algorithms, encapsulates each one, and makes them interchangeable so the algorithm can vary independently from the clients that use it.

How to Implement the Strategy Pattern in PHP

1Step 1: Define the strategy interface

interface SortStrategy
{
    /** @param int[] $data */
    public function sort(array &$data): void;
}

2Step 2: Implement concrete strategies

class BubbleSort implements SortStrategy
{
    public function sort(array &$data): void
    {
        $n = count($data);
        for ($i = 0; $i < $n - 1; $i++) {
            for ($j = 0; $j < $n - $i - 1; $j++) {
                if ($data[$j] > $data[$j + 1]) {
                    [$data[$j], $data[$j + 1]] = [$data[$j + 1], $data[$j]];
                }
            }
        }
    }
}

class QuickSort implements SortStrategy
{
    public function sort(array &$data): void
    {
        sort($data); // Using PHP's built-in sort for simplicity
    }
}

3Step 3: Implement the context that uses a strategy

class Sorter
{
    public function __construct(private SortStrategy $strategy) {}

    public function setStrategy(SortStrategy $strategy): void
    {
        $this->strategy = $strategy;
    }

    /** @param int[] $data */
    public function sort(array &$data): void
    {
        $this->strategy->sort($data);
    }
}

// Usage
$sorter = new Sorter(new BubbleSort());
$data = [5, 3, 8, 1, 2];
$sorter->sort($data);
print_r($data); // [1, 2, 3, 5, 8]

$sorter->setStrategy(new QuickSort());
$data2 = [9, 4, 7, 6];
$sorter->sort($data2);

Strategy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Strategy Pattern in the Real World

Consider a GPS app offering route options: fastest, shortest, or avoid tolls. The destination is the same, but the navigation algorithm changes based on your preference. The app (context) simply hands the journey off to whichever routing strategy you selected; you can switch strategies mid-trip without the app needing to change its structure.