HomePHP Validating User Input with the Strategy Pattern
Validating User Input with the Strategy Pattern
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.
Going back quickly to the topics covered in the first tutorial of the series, certainly you'll remember that I explained the foundations of the strategy design pattern, and complemented the theory with some practical examples of how to apply this handy pattern in PHP 5.
Based upon this scenario, I developed a set of simple PHP classes. One of them was defined as a strategy selector, handy for determining what type of format (HTML or XML) had to be applied to certain file data. The other ones were tasked with implementing a given formatting strategy.
Although the example that I just described may seem rather basic, it shows in a nutshell the logic that drives the strategy pattern: on one hand there's a class that sets the context as to where a predefined group of strategies will be applied, while on the other hand there's one or more classes that implement these strategies.
However, now that you hopefully digested the contents of the first article of the series, let me tell you what you'll learn in this final tutorial. In the next few lines I'm going to demonstrate how to use the strategy pattern in a useful case, that is validating user-supplied input. Sound like an interesting experience, right?
Now that you know the purpose of this last part of the series, let me show you how to implement the strategy pattern to check a wide range of user inputs. Let's begin now!