Patterns / Behavioral patterns
image

<?php

interface Strategy {
    function doOperation(int $a, int $b);
}

//ConcreteStrategy
class AddStrategy implements Strategy {
    function doOperation(int $a, int $b) {
        return $a + $b;
    }
}

//ConcreteStrategy
class SubstractStrategy implements Strategy {
    function doOperation(int $a, int $b) {
        return $a - $b;
    }
}

//Context
class Calc {
    private $strategy;

    function execute(int $a, int $b): int {
        if ($this->strategy == null
            return 0;
        return $this->strategy->doOperation($a, $b);
    }

    function setStrategy(Strategy $strategy) {
        $this->strategy = $strategy;
    }
}

$calc = new Calc();
$result1 = $calc->execute(53);
//result1 is 0
echo $result1, "\n";

$calc->setStrategy(new AddStrategy());
$result2 = $calc->execute(53);
//result2 is 8
echo $result2, "\n";

$calc->setStrategy(new SubstractStrategy());
$result3 = $calc->execute(53);
//result3 is 2
echo $result3, "\n";


Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.