Created
April 8, 2023 17:09
-
-
Save Azer5C74/0fc178b2336ba5102a625ef859bf4d27 to your computer and use it in GitHub Desktop.
This is an example of strategy pattern usage written in php. It helps to encapsulate a family of algorithms that perform similar functions, here we tried encapsulating various logging methods to an interface and making them interchangeable.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Defining a family of algorithms | |
class LogToFile implements Logger | |
{ | |
public function log($data) | |
{ | |
var_dump('Log the data to a file.'); | |
} | |
} | |
class LogToDatabase implements Logger | |
{ | |
public function log($data) | |
{ | |
var_dump('Log the data to a database.'); | |
} | |
} | |
class LogToWebService implements Logger | |
{ | |
public function log($data) | |
{ | |
var_dump('Log the data to a web service.'); | |
} | |
} | |
// encapsulating the algorithms and making them interchangeable | |
interface Logger | |
{ | |
public function log($data); | |
} | |
class App | |
{ | |
public function log($data, Logger $logger = null) | |
{ | |
// setting log to file as a default logging method | |
$logger = $logger ?: new LogToFile(); | |
$logger = $data; | |
} | |
} | |
$app = new App; | |
$app->log('Some logging info here.', new LogToDatabase); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment