HomePHP Page 4 - Validating User Input with the Strategy Pattern
Validating user-supplied data - 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.
To demonstrate how all the classes that you learned in previous sections of this tutorial can be used to check the validity of different types of data, below I coded a short script that shows some illustrative cases where the validation strategy selector verifies firstly alphabetic and alphanumeric values, and lastly numbers and email addresses.
Having said that, the corresponding examples look like this:
try{ // example using the 'Strategy pattern' $strategyAlpha=new ValidationStrategySelector('alpha'); echo $strategyAlpha->validateData(123); /* displays the following: Input data is not valid! */ $strategyAlphanum=new ValidationStrategySelector('alphanum'); echo $strategyAlphanum->validateData('ABC123'); /* displays the following Input data is OK! */ $strategyNumber=new ValidationStrategySelector('number'); echo $strategyNumber->validateData('ABC'); /* displays the following: Input data is not valid! */ $strategyEmail=new ValidationStrategySelector('email'); $strategyEmail->validateData('inexistent-user@domain.com'); /* displays the following: Input data is not valid! */ } catch(Exception $e){ echo $e->getMessage(); exit(); }
As you can see, the prior examples illustrate in a step-by-step format how the strategy design pattern can be used in a real situation, in this particular case, aimed at validating a wide variety of data types.
As you saw, the first two examples use the validation strategy selector to verify alphabetic and alphanumeric values in turn, and also display the respective results. Finally, the other two cases demonstrate how to use the same selector to validate numeric data and an email address.
All right, I believe that all these examples should give you an approximate idea of how the strategy pattern can be used in a real-world situation. In the last section of this tutorial I'm going to list all the classes that you learned here. By doing so, you'll have available at one single place the complete source code required to implement the strategy pattern in PHP 5.
As you know, the last section of this article is just one click away, so go forward and keep reading.