To demonstrate in a quick and dirty way how flexible the earlier “FloatValidator” class can be, below I coded a somewhat trivial script which shows how to use the class as a standalone component. Check it out: // create an instance of the float validator class $floatValidator = new FloatValidator('This is a test string'); // validate the supplied value if (!$floatValidator->validate()) { echo $floatValidator->getFormattedError(); /* displays the following The value This is a test string is incorrect. Please enter a float value. */ } else { echo ' The data that you entered is correct.'; } Done. As you can see, using an instance of the previous “FloatValidator” class in an independent way is a straightforward process that doesn’t bear any further discussion. However, it’s worth pointing out that the above script may produce erroneous results, particularly when checking numeric values. These glitches occur due to the behavior of the FILTER_VALIDATE_FLOAT constant. Thus, if you need to fix these little bugs, please read the official PHP filters documentation here: http://php.net/manual/en/ref.filter.php Having clarified that, I’m sure that at this point you have a clearer idea of how useful the Strategy pattern can be when checking incoming data in a modular way. However, the sample validation program being developed here still has a pretty limited functionality that needs to be enhanced. This will be done, of course, in future articles in this series. Final thoughts In this third installment of the series, I proceeded to create a brand new strategy class, which was provided with the functionality required to check whether or not a supplied input value is a float number. While the addition of this class does contribute to extending the capabilities of the sample validation program that I’m currently building in this series, it’s fair to say that it can be enhanced even further. You may be wondering how. Well, it’d be relatively easy to add another strategy class to the program, and make this one able to validate email addresses. This would make it possible to assemble a wider range of validation strategies at run time, which speaks for itself about the benefits introduced by Composition. In the next article I’m going to define this new email checking class. Here’s my final piece of advice: don’t miss the upcoming tutorial!
blog comments powered by Disqus |
|
|
|
|
|
|
|