Strategy Pattern in PHP

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.php

interface confirmation

{

//method name confirm

public function Confirm();

}

?>

 

Let's create a "class.Emailconfirmation.php" file.

 

<?php

//include interface.confirm.php

include_once("interface.confirm.php");

//create class Emailconfirmation

class EmailConfirmation implements confirmation

{

//method name confirm

public function confirm()

{

//do something to confirm the user by Email

}

}

?>


And next I will create a "class.faxconfirmation.php" file.

 

<?php

//include class.emailconfirmation.php

include_once("class.emailconfirmation.php");

//implements confirmation interface

class FaxConfirmation implements confirmation

{

// create method confimation

public function confirm()

{

//do something to confirm the user by Fax

}

}

?>

 

And next I will create a "class.SMSconfirmation.php" file.

 

<?php

//include class.faxconfirmation.php

include_once("class.faxconfirmation.php");

//implements confirmation interface

class SMSConfirmation implements confirmation

{

public function confirm()

{

//do something to confirm the user by SMS

}

}

?>

 

Now I will use this code:

 

<?php

//include three files

include_once("class.Emailconfirmation.php");

include_once("class.Faxconfirmation.php");

include_once("class.SMSconfirmation.php");

//user object

$user = new User();

$confirmation = $user->getconfirmation();

switch ($confirmation)

{

case "email":

//object of Emailconfirmation class

$objconfirmation = new Emailconfirmation();

break;

case "sms":

//object of SMSconfirmation class

$objconfirmation = new SMSconfirmation();

break;

case "fax":

//object of Faxconfirmation class

$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 implement that method on their own.

Up Next
    Ebook Download
    View all
    Learn
    View all