HomePHP Using Multiple Strategy Classes with the Strategy Design Pattern
Using Multiple Strategy Classes with the Strategy Design Pattern
Being one of the most popular contenders in the exciting, but very often complex, terrain of software design, the Strategy design pattern is a well-trusted paradigm. It allows you to build more flexible and efficient applications by appealing to the functionality of two of the big pillars of solid object-oriented programming: favoring Composition over Inheritance, and encapsulating the concepts that vary. This is the conclusion to a six-part series that shows you how to use the Strategy design pattern to validate incoming data.
As with other design patterns, the implementation of the Strategy pattern isn't subject to a specific programming language or context, and in fact it may vary slightly from case to case. This doesn't imply, though, that its use in real-world projects must be a painful and annoying experience. In reality, applying the model imposed by the pattern is most of the time a straightforward process, and it's even easier to accomplish when using a language as PHP, whose learning curve is remarkably flat.
To prove how easy it is to apply the Strategy pattern in a real-world case, in previous parts of the series I developed a set of loosely-coupled classes. Each one was responsible for implementing a specific validation strategy, ranging from checking integer and float numbers to verifying email addresses and URLs. So far, I've demonstrated how to use the classes as standalone components; now it's time to show how to put them to work together, so you can see how simple is to use these classes like LEGO blocks and assemble more complex strategies at run time.
With that premise in mind, in this last chapter of the series I'm going to build a sample application. It will use the aforementioned strategy classes to validate a set of inputted values in a very modular and flexible way. This instructive process will involve the use of Composition and Dependency Injection as well.
Now, it's time to leave the theory behind us and show how to put the Strategy pattern to work for us in a truly useful fashion. Let's get going!