HomePHP Page 3 - Validating User Input with the Strategy Pattern
Building some strategy classes - 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 you'll certainly recall from the previous section, the validation strategy selector spawns four different objects, and each one of them is responsible for validating a specific type of data. Therefore, taking this situation into account, below I listed the respective signatures corresponding to these strategy classes.
Here they are, so have a look at them, please:
// 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; } }
As shown above, each of the four strategy classes listed previously implements differently the same "validateData()" method to check a diverse range of user inputs, such as alphabetic and alphanumeric values, and number and email addresses.
Of course, it's possible to extend the initial validation capacity of the whole data checking system even more, simply by adding new strategy classes to the existing ones. This is definitely a process that can be performed with minor hassles.
So far, so good. At this point, you've seen not only how the validation strategy selector looks, but how the four strategy classes have been properly defined. This is very convenient for understanding the schema imposed by the strategy pattern.
So, the question that comes up is: what's the next step now? Well, considering that you already grasped the logic implemented by all the classes that I defined so far, it's time to move forward and see a concrete example where a data validation system is created by using the aforementioned classes.
Want to see how the strategy pattern is applied to validate user-supplied input? Jump straight into the following section and keep reading.