HomePHP Validating Incoming Data with the Strategy Design Pattern
Validating Incoming Data with the Strategy Design Pattern
If you’ve been doing some research lately on the web about how to implement different design patterns, be it in Java, PHP or Python, you'll probably have noticed that the Strategy pattern is one of the most popular contenders in the field. It has been covered countless times in all types of media, ranging from books and magazines to e-zines and personal blogs. In this article series, I'll show you how to use this popular design pattern to accomplish one of the more common tasks a website must perform: validating user-supplied data.
Logically, there’s a reason for the Strategy design pattern's well-deserved popularity: unlike the Composite and Decorator patterns, which are also important to pattern-driven programming, the logic that stands behind Strategy is much easier to grasp, and its implementation in several languages is fairly straightforward as well. While the aforementioned Composite and Decorator are powerful paradigms that permit you to tackle certain software development problems with elegance and efficiency, the truth is that they’re also pretty confusing to understand, at least at first.
On the other hand, the Strategy pattern not only has a flatter learning curve than its cousins, but it allows you to implement two basic principles of object-oriented programming that you’ve probably heard before: “Favor Composition over Inheritance” and “Encapsulate the concept that varies.” Yes, Strategy is a typical case where the power of Composition permits you to create loosely-coupled classes that can be consumed by client code or other classes through a highly-encapsulated interface, without having to create a redundant hierarchy of objects.
With all these goodies at hand for free, it’s logical to think that implementing the Strategy pattern in PHP is a fairly straightforward process. Well, that’s correct, too. And to demonstrate this, in the course of this article series I’ll be showing how to implement the pattern in a real-world case: validating user supplied data. In doing so, you hopefully will learn the basic concepts that surround the application of the Strategy pattern, in addition to building a highly-modular data validation program, which you’ll be able to tweak and improve at will.
Now, it’s time to get rid of the preliminaries and start taking advantage of the functionality offered by the Strategy pattern in PHP. Let’s go!