Skip to content
Advertisement

I’m having a little trouble implementing the Strategy pattern

I confess that I’m having a bit of difficulty implementing the strategy pattern in a program that aims to display a different message daily (Ex. Message of the day…), but on special dates there may be some variations (Ex. Merry Christmas : Message from day…), could someone give me an example of how I “could” make this implementation in php?

Advertisement

Answer

I haven’t touched PHP in a while, so forgive any syntax errors, but the general idea would be to have a class where you can set the strategy you want (in this case, how you want to display the message), and then based on whether or not it’s a holiday, you can swap in the holiday strategy, something like:

class DailyMessage {

    private $strategy;
    private $message;

    public function __construct(string $message, Strategy $strategy) {
        $this->message = $message;
        $this->strategy = $strategy;
    }

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

    public function getMessage() {
        return $this->strategy->format($this->getMessage());
    }
}

interface Strategy {
    public function format($message);
}

class DefaultStrategy implements Strategy {
    public function format($message) {
        return $message;
    }
}

class HolidayStrategy implements Strategy {
    private $greeting;
    __constructor($greeting) {
        $this->greeting = $greeting;
    }
    public function format($message) {
        return $greeting . ': ' . $message;
    }
}

$dm = new DailyMessage($messageOfTheDay, new DefaultStrategy());
$holidays = ["Dec 25" => "Merry Christmas", "Oct 31" => "Happy Halloween"];
$today = date('M j');
if (array_key_exists($today, $holidays)) {
    $dm->setStrategy(new HolidayStrategy($holidays[$today]));
}
echo $dm->getMessage();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement