Mastering the Strategy Pattern in PHP: A Comprehensive Guide

Explore the Strategy Pattern in PHP, learn how to define interchangeable algorithms, and enhance your software design skills with practical examples and best practices.

7.9 Strategy Pattern

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm’s behavior at runtime. It defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern is particularly useful when you need to switch between different algorithms or strategies based on the context.

Intent

The primary intent of the Strategy Pattern is to define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern allows the algorithm to vary independently from the clients that use it.

Key Participants

  1. Strategy Interface: Declares a common interface for all supported algorithms.
  2. Concrete Strategies: Implement the algorithm defined in the Strategy interface.
  3. Context: Maintains a reference to a Strategy object and delegates the algorithm execution to the current Strategy.

Applicability

  • Use the Strategy Pattern when you have multiple related algorithms that need to be interchangeable.
  • When you want to avoid exposing complex, algorithm-specific data structures.
  • When a class defines many behaviors and these appear as multiple conditional statements in its operations.

Implementing Strategy in PHP

Let’s dive into implementing the Strategy Pattern in PHP. We’ll create a simple example involving different sorting algorithms.

Step 1: Define the Strategy Interface

First, we define a SortStrategy interface that declares a method for sorting.

1<?php
2
3interface SortStrategy
4{
5    public function sort(array $data): array;
6}

Step 2: Implement Concrete Strategies

Next, we implement different sorting algorithms as concrete strategies.

 1<?php
 2
 3class BubbleSortStrategy implements SortStrategy
 4{
 5    public function sort(array $data): array
 6    {
 7        $n = count($data);
 8        for ($i = 0; $i < $n; $i++) {
 9            for ($j = 0; $j < $n - $i - 1; $j++) {
10                if ($data[$j] > $data[$j + 1]) {
11                    $temp = $data[$j];
12                    $data[$j] = $data[$j + 1];
13                    $data[$j + 1] = $temp;
14                }
15            }
16        }
17        return $data;
18    }
19}
20
21class QuickSortStrategy implements SortStrategy
22{
23    public function sort(array $data): array
24    {
25        if (count($data) < 2) {
26            return $data;
27        }
28        $left = $right = [];
29        reset($data);
30        $pivot_key = key($data);
31        $pivot = array_shift($data);
32        foreach ($data as $k => $v) {
33            if ($v < $pivot)
34                $left[$k] = $v;
35            else
36                $right[$k] = $v;
37        }
38        return array_merge($this->sort($left), [$pivot_key => $pivot], $this->sort($right));
39    }
40}

Step 3: Create the Context

The Sorter class acts as the context, which uses a strategy to perform its behavior.

 1<?php
 2
 3class Sorter
 4{
 5    private SortStrategy $strategy;
 6
 7    public function __construct(SortStrategy $strategy)
 8    {
 9        $this->strategy = $strategy;
10    }
11
12    public function setStrategy(SortStrategy $strategy): void
13    {
14        $this->strategy = $strategy;
15    }
16
17    public function sort(array $data): array
18    {
19        return $this->strategy->sort($data);
20    }
21}

Step 4: Using the Strategy Pattern

Now, let’s see how we can use the Sorter class with different strategies.

 1<?php
 2
 3$data = [64, 34, 25, 12, 22, 11, 90];
 4
 5$sorter = new Sorter(new BubbleSortStrategy());
 6echo "Bubble Sort: ";
 7print_r($sorter->sort($data));
 8
 9$sorter->setStrategy(new QuickSortStrategy());
10echo "Quick Sort: ";
11print_r($sorter->sort($data));

Design Considerations

  • Flexibility: The Strategy Pattern provides flexibility in choosing algorithms at runtime.
  • Complexity: It can increase the number of classes in your application.
  • Performance: Switching strategies at runtime can have performance implications.

PHP Unique Features

PHP’s dynamic nature and support for interfaces make it an excellent fit for implementing the Strategy Pattern. The use of type declarations and type hinting enhances code readability and maintainability.

Differences and Similarities

The Strategy Pattern is often confused with the State Pattern. While both patterns involve changing behavior at runtime, the Strategy Pattern is focused on selecting algorithms, whereas the State Pattern is concerned with changing the object’s state.

Visualizing the Strategy Pattern

To better understand the Strategy Pattern, let’s visualize the relationships between the components using a class diagram.

    classDiagram
	    class SortStrategy {
	        <<interface>>
	        +sort(array): array
	    }
	    class BubbleSortStrategy {
	        +sort(array): array
	    }
	    class QuickSortStrategy {
	        +sort(array): array
	    }
	    class Sorter {
	        -SortStrategy strategy
	        +setStrategy(SortStrategy): void
	        +sort(array): array
	    }
	    SortStrategy <|.. BubbleSortStrategy
	    SortStrategy <|.. QuickSortStrategy
	    Sorter --> SortStrategy

Use Cases and Examples

The Strategy Pattern is widely used in various scenarios, such as:

  • Sorting Algorithms: As demonstrated in our example, different sorting strategies can be applied based on the context.
  • Payment Processing: Different payment methods (e.g., credit card, PayPal, bank transfer) can be encapsulated as strategies.
  • Compression Algorithms: Different file compression algorithms can be applied based on the file type or user preference.

Try It Yourself

Experiment with the Strategy Pattern by implementing additional sorting algorithms, such as Merge Sort or Insertion Sort. Modify the Sorter class to handle different data types or add logging functionality to track the sorting process.

Knowledge Check

  • What is the primary intent of the Strategy Pattern?
  • How does the Strategy Pattern differ from the State Pattern?
  • Can you think of other scenarios where the Strategy Pattern might be useful?

Embrace the Journey

Remember, mastering design patterns is a journey. The Strategy Pattern is just one of many tools in your software design toolkit. As you continue to explore and experiment, you’ll gain a deeper understanding of how to apply these patterns effectively in your projects. Keep learning, stay curious, and enjoy the process!

Quiz: Strategy Pattern

Loading quiz…
Revised on Thursday, April 23, 2026