strategy pattern in php

The Strategy Pattern is a design pattern in Object-Oriented Programming that allows you to define a family of algorithms, encapsulate each one as an object, and make them interchangeable at runtime. In PHP, you can apply the Strategy Pattern to improve the flexibility of your code and allow for easier switching of algorithms or behaviors.

To implement the Strategy Pattern in PHP, you can follow these steps:

  1. Create the Strategy interface that defines the common methods to be implemented by each Strategy:
main.php
interface Strategy {
    public function execute($data);
}
59 chars
4 lines
  1. Create the Concrete Strategies that implement the Strategy interface with their own versions of the methods:
main.php
class ConcreteStrategyA implements Strategy {
    public function execute($data) {
        // Implementation A
    }
}

class ConcreteStrategyB implements Strategy {
    public function execute($data) {
        // Implementation B
    }
}
239 chars
12 lines
  1. Create the Context class that holds a reference to a Strategy object and can switch between different Concrete Strategies:
main.php
class Context {
    private $strategy;

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

    public function executeStrategy($data) {
        return $this->strategy->execute($data);
    }
}
239 chars
12 lines
  1. Finally, you can use the Context class to switch between different Concrete Strategies and execute them:
main.php
// Create the Context
$context = new Context();

// Set a Concrete Strategy
$context->setStrategy(new ConcreteStrategyA());

// Execute the Strategy
$result = $context->executeStrategy($data);
193 chars
9 lines

With the Strategy Pattern, you can easily switch between different Concrete Strategies by simply setting the desired Strategy object in the Context. This allows for greater flexibility and easier encapsulation of algorithms or behaviors in your code.

gistlibby LogSnag