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!