Done!

The Strategy Pattern - Design Pattern in PHP


Strategy pattern is used when there are multiple ways of achieving a task. For e.g., say if a task is to log, then there could be different strategies to accomplish this: LogToFile, LogToDatabase, LogToWebService.

These strategies may use different set of algorithms to achieve a task. LogToFile my implement one set of algorithms, where as LogToDatabase may implement completely different set of algorithm.

To implement strategy pattern:

Firstly, define a set (family) of algorithms

class LogToFile() {}
class LogToDatabase() {}
class LogToWebServices() {}

Secondly, make these strategies interchangable by implementing a contract or interface

 /**
  * To make algorithms interchangable
  */
interface Logger {
    public function log($data);
}

/**
 * Make different strategies interchangable by implementing Logger interface 
 */
class LogToFile implements Logger {
    public function log($data) {
        var_dump("Log to a file data : " . $data);
    }
}

class LogToDatabase implements Logger {
    public function log($data) {
        var_dump("Log to a Database : " . $data);
    }
}

class LogToWebServices implements Logger {
    public function log($data) {
        var_dump("Log to a Web SErvices : " .  $data);
    }
}

By doing so, at runtime we can pass different strategies (LogToFile or LogToDatabase) to accomplish a task

class App {
    public function log($data, Logger $logger) {
        $logger->log($data);
    }
}

(new App)->log('User Deleted', new LogToFile);
(new App)->log('User Deleted', new LogToDatabase);
(new App)->log('User Deleted', new LogToWebServices);