The strategy design pattern can be very useful in the context of form validation. This article, the first of two parts, will introduce you to the strategy pattern and give you some idea of how you can use it in your own PHP applications.
Whether youíre a PHP developer who has been using this useful server-side scripting language for a while, or a seasoned programmer who has spent many years developing PHP-driven web applications, itís highly probable that you have already used (deliberately or not) a design pattern.
While this isnít a fact that is going to change the way you create your PHP programs permanently, the truth is that there are certain design patterns that are much more common to implement during the development of specific web applications than others.
Naturally, this concept may sound strange at first, particularly if youíre just starting to dig deeper into the huge and fascinating terrain of PHP-based programming, but consider this: how many times have you used the "new" PHP keyword to create an instance of a particular class? Or, more to the point, how many times have you utilized the "&" operator to avoid working with multiple instances of that class?
Probably the answer to the above questions is tens or hundreds of times, right? In these cases you used a basic implementation of the Factory and Singleton patterns respectively, maybe without being aware of it.
As you can see, there are certain design patterns that are more usually applied than others. Thatís exactly the case with the subject of this article, the strategy pattern. To put things more clearly, Iím sure that you always validate adequately all the forms included in your web sites. First off, you create a few validation functions (or classes), then use these functions to check the validity of the data supplied by users, and finally determine the course of action to be taken accordingly.
In the example that I described above, you first selected a context where the corresponding form validation was going to take place, and then applied a data checking strategy to establish programmatically how different types of user inputs will be verified.
Certainly, this is a concrete implementation of the strategy design pattern, in a situation that should be familiar to you! In other words, when this pattern is applied, there will be a predefined context (in object-based programming this is represented by a context class) that will be capable of selecting what type of action must be taken, in accordance with the requirement of a specific strategy (again, in OOP this is achieved by coding different extensions of a class interface).
Now that you know at least in theory how the strategy pattern works, in this two-part series Iím going to demonstrate the practical side of this topic. I will provide you with some illustrative examples that hopefully will help you understand how the pattern can be included in your own PHP applications.
Ready to face this challenge? All right, letís go!