Validating User Input with the Strategy Pattern - Listing all the classes required to implement the strategy pattern
(Page 5 of 5 )
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.
See you in the next PHP tutorial!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |