how to strategy pattern in php

The Strategy Pattern is a behavioral design pattern that allows a user to define a family of algorithms, encapsulate each one, and make them interchangeable. In order to use the Strategy Pattern in PHP, follow these steps:

  1. Define an abstract Strategy class that includes an abstract method for executing the algorithm.
main.php
abstract class Strategy {
  abstract function execute();
}
59 chars
4 lines
  1. Define concrete implementations of the Strategy class, each with a unique implementation of the execute method.
main.php
class ConcreteStrategyA extends Strategy {
  function execute() {
    // implementation A
  }
}

class ConcreteStrategyB extends Strategy {
  function execute() {
    // implementation B
  }
}
193 chars
12 lines
  1. Create a Context class to provide a interface for the clients to use the strategy. The context stores a reference to a Strategy object and delegates the work to the strategy object.
main.php
class Context {
  private $strategy;
  
  function __construct(Strategy $strategy) {
    $this->strategy = $strategy;
  }
  
  function executeStrategy() {
    $this->strategy->execute();
  }
}
194 chars
12 lines
  1. Use the context to execute the algorithm from the selected strategy.
main.php
$strategyA = new ConcreteStrategyA();
$strategyB = new ConcreteStrategyB();

$context = new Context($strategyA);
$context->executeStrategy(); // this will execute implementation A

$context = new Context($strategyB);
$context->executeStrategy(); // this will execute implementation B
284 chars
9 lines

In summary, the Strategy Pattern promotes the creation of interchangeable algorithms that are encapsulated in their own Strategy implementations. This allows clients of the code to select different algorithms at runtime without having to know the specifics of the algorithm itself, thus reducing coupling and promoting flexibility.

gistlibby LogSnag