In reality, testing the functionality of the "UrlValidator" class defined in the preceding segment is an extremely trivial process. It's reduced to first spawning an instance of the class in question, and then calling its "validate()" method. Obviously, the best way to understand this is by means of example, so below I coded one for you that checks to see if the string "http://www.devshed.com" is a well-formed URL. Here it is: // create an instance of the URL validator class $urlValidator = new UrlValidator('http://www.devshed.com'); // validate the supplied value if (!$urlValidator->validate()) { echo $urlValidator->getFormattedError(); } else { echo 'The data that you entered is correct.'; /* displays the following The data that you entered is correct. */ } Well, as one might expect, the above example worked like a charm, as the value passed to the constructor of the URL validator object is really a valid Uniform Resource Locator. However, keep in mind that the FILTER_VALIDATE_URL constant used internally by the "filter_var()" PHP function only verifies if the format of the inputted value is RFC-compliant. If you need to perform a stricter validation, consider implementing this functionality through a method of your own. The experience will be enriching and -- why not? -- also fun. Final thoughts In this penultimate episode of the series, I built yet another strategy class, which in this case was responsible for validating URLs using the "filter_var()" built-in PHP function. This process was pretty similar to defining other previous strategy classes, which means that you shouldn't have major difficulties understanding its underlying logic. Now, take a deep breath, relax and think about the scenario created at this point. On one hand there's a form helper that accepts instances of different strategy classes to validate a decent variety of data, while on the other hand, the strategy classes are capable of performing specific checking tasks as isolated components. What can we do with all these elements? Yes, you guessed right! By putting them to work together, it'd be possible to assemble different validation strategies at runtime with extreme ease and without having lots of code duplication. The only requirement to achieve this would be to create client code that consumes the interfaces exposed by the involved classes. That's exactly what I plan to cover in the last article, so don't miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|