An Intro to Strategy Design Pattern in PHP

The Strategy design pattern (aka Policy pattern) allows you to pick the algorithm you want at runtime and it decouples the algorithm from where it's used. In other words, the Strategy pattern is used when we need to choose between similar classes that are different only in their implementation and in this tutorial, we will see how to implement this pattern in PHP programming language.

In situations that we need to make a decision based on a couple of parameters to choose a policy over the others, we have to create an interface which all those classes implement and choose our preferred class at runtime.

To clarify how this design pattern can be created, let's make an analogy to a real-world example. Imagine based on the number of shopping items, you decide how to go shopping:

<?php
interface shoppingStrategy
{
    public function go();
}

class GoOnFoot implements shoppingStrategy
{
    public function go()
    {
        echo "Because the numbers of items is less than 5, you can go shopping on foot";
    }
}

class GoByCar implements shoppingStrategy
{
    public function go()
    {
        echo "Because the numbers of items is greater than 5, you can go shopping by car";
    }
}

class Shopping
{
    private $numberOfItems;

    public function __construct($numberOfItems)
    {
        $this->numberOfItems = $numberOfItems;
    }

    public function goShopping()
    {
        if ($this->numberOfItems < 5) {
            $goingStrategy = new GoOnFoot();
        } else {
            $goingStrategy = new GoByCar();
        }
        return $goingStrategy->go();
    }
}

$obj1 = new Shopping(10);
$obj1->goShopping();
echo "\n";
$obj2 = new Shopping(3);
$obj2->goShopping();

First, an interface called shoppingStrategy is created which has only a go() method and the following GoOnFoot and GoByCar classes must implement it. In the shopping class, we assign the constructor parameter to the $numberOfItems property and in the goShopping() method check to see if the value of this property is greater than 5 or not. Based on the value of this property, we assign the suitable class to the $goingStrategy variable and at the end of the day our go() method is returned.

In lines 43 to 47, two different objects are created from Shopping class with two different arguments; one is greater than 5 and the other is smaller; so in the output we'll have:

Because the numbers of items is greater than 5, you can go shopping by car
Because the numbers of items is less than 5, you can go shopping on foot

As you can see, by using the Strategy pattern, we can on the fly decide which way to go based on our parameter/parameters.

by Behzad Moradi on 2019-08-12

Login to add your comment