As I expressed in the past segment, it's ridiculously easy to implement an entirely different validation strategy using the set of classes created previously. For demonstration purposes, say that you need to determine if a couple of values collected via an HTML form are an integer and a valid URL respectively. In a case like this, the entire checking process should be performed in the following way:
// include autoloader
$autoloader = Autoloader::getInstance();
// create an instance of the form helper
$formHelper = new FormHelper();
// add a couple of validators to the form helper
// validate inputted data and display all error messages in one go
echo 'The submitted data is correct!';
displays the following
The submitted data is correct!
See how easy it is to switch over different validation strategies at run time? I bet you do! Since in this case the components responsible for checking inputted values are highly encapsulated objects, performing more complex (or stricter) validation is reduced to creating a few additional validator classes. It's that simple, really.
And with this final example, I'm finishing this humble series on implementing the Strategy design pattern in PHP. Now that you surely have a clearer idea of the logic that stands behind this popular pattern, you may want to use it for adding extra flexibility to your own web applications.
It's hard to believe, but we've come to the end of this series. Hopefully the whole experience has been educational and even fun, as you learned how to implement the Strategy design pattern to tackle a real-world problem: validating incoming data in a truly flexible and modular way.
Taking into account the pattern's flat learning curve and the numerous benefits that it introduces into the application of good object-oriented programming techniques, you may want to consider implementing it in your coming PHP project.
Meet you in the next PHP tutorial!
blog comments powered by Disqus