Introduction
This article explains the Strategy Pattern in PHP. One of the common issues we encounter while programming is that must create decisions on completely different methods. Strategy Patterns have a common pattern that helps us to create decisions on completely different cases, more simply. To know this is good, let us use the scenario where you are developing a notification program. This notification program can check the given choices for a user. A user might want to be notified in many ways, like email, SMS, or Fax. Your program should check the available choices to contact that user and so create a call upon that. This case will simply be solved by the Strategy Pattern.
Strategy pattern
Example
First of all, I will create an interface.
- <?php
-
- interface confirmation
- {
-
- public function Confirm();
- }
- ?>
Let's create a "class.Emailconfirmation.php" file.
- <?php
-
- include_once("interface.confirm.php");
-
- class EmailConfirmation implements confirmation
- {
-
- public function confirm()
- {
-
- }
- }
- ?>
And next I will create a "class.faxconfirmation.php" file.
- <?php
-
- include_once("class.emailconfirmation.php");
-
- class FaxConfirmation implements confirmation
- {
-
- public function confirm()
- {
-
- }
- }
- ?>
And next I will create a "class.SMSconfirmation.php" file.
- <?php
-
- include_once("class.faxconfirmation.php");
-
- class SMSConfirmation implements confirmation
- {
- public function confirm()
- {
-
- }
- }
- ?>
Now I will use this code:
- <?php
-
- include_once("class.Emailconfirmation.php");
- include_once("class.Faxconfirmation.php");
- include_once("class.SMSconfirmation.php");
-
- $user = new User();
- $confirmation = $user->getconfirmation();
- switch ($confirmation)
- {
- case "email":
-
- $objconfirmation = new Emailconfirmation();
- break;
- case "sms":
-
- $objconfirmation = new SMSconfirmation();
- break;
- case "fax":
-
- $objconfirmation = new Faxconfirmation();
- break;
- }
- $objconfirmation->confirm();
- ?>
In the code above I have used three classes known as "SMSconfirmation", "Emailconfirmation", and "Faxconfirmation". Of these classes implement the confirmation interface, that includes a method named notify. Every one of those categories implements that method on their own.