HomePHP Page 5 - Validating User Input with the Strategy Pattern
Listing all the classes required to implement the strategy pattern - PHP
The strategy design pattern is applied much more often than you might think, so if you want to find out how to implement it with PHP 5, this article should guide you through the whole learning process. Welcome to the final installment of the series that began with “Introducing the Strategy Pattern.” In two parts, this series walks you through the key points of how the strategy pattern works, and accompanies its theoretical concepts with copious hands-on examples.
As I promised before, here are all the classes that I built over the course of this tutorial to apply the strategy pattern with PHP 5:
// define 'ValidationStrategySelector' class class ValidationStrategySelector{ private $strategy=NULL; public function __construct($strategy){ if($strategy!='alpha'&&$strategy!='alphanum'&&$strategy! ='number'&&$strategy!='email'){ throw new Exception('Invalid parameter for validation strategy!'); } switch($strategy){ case "alpha": $this->strategy=new StrategyAlphabetic(); break; case "alphanum": $this->strategy=new StrategyAlphanumeric(); break; case "number": $this->strategy=new StrategyNumber(); break; case "email": $this->strategy=new StrategyEmail(); break; } } public function validateData($inputData){ if(!$this->strategy->validateData($inputData)){ return 'Input data is not valid!'; } return 'Input data is OK!'; } } // define 'StrategyAlphabetic' class class StrategyAlphabetic{ public function validateData($inputData){ if(!$inputData||!preg_match("/^[a-zA-Z]+$/",$inputData)){ return false; } return true; } } // define 'StrategyAlphanumeric' class class StrategyAlphanumeric{ public function validateData($inputData){ if(!$inputData||!preg_match("/^[a-zA-Z0-9]+$/",$inputData)){ return false; } return true; } } // define 'StrategyNumber' class class StrategyNumber{ public function validateData($inputData){ if(!$inputData||!is_numeric($inputData)){ return false; } return true; } } // define 'StrategyEmail' class class StrategyEmail{ public function validateData($inputData){ if(!$inputData||!preg_match("/.+@.+..+./",$inputData)||! checkdnsrr(array_pop(explode("@",$inputData)),"MX")){ return false; } return true; } }
That's it. As usual with all my articles, feel free to modify the signature of all the classes that I showed here so you can acquire a better understanding of this pattern. Have a good time!
Final thoughts
Unfortunately, we've come to the end of this series. However, I hope that after reading these two articles, you'll have a better idea not only of how the strategy pattern works, but how it can be used in real situations.