As one might expect, using the email validator defined in the previous section as a standalone component is a straightforward process that can be tackled with minor efforts. In reality, checking the validity of a supplied email address via this concrete strategy class is reduced to coding a script similar to the one shown below: // create an instance of the email validator class $emailValidator = new EmailValidator('alejandrodomain.com'); // validate the supplied value if (!$emailValidator->validate()) { echo $emailValidator->getFormattedError(); /* displays the following The value alejandrodomain.com is incorrect. Please enter a valid email address.. */ } else { echo ' The data that you entered is correct.'; } There you have it. If you've ever built an object-oriented application that checks user-supplied email addresses, then the earlier code fragment should be pretty familiar to you. At the risk of being repetitive, keep in mind that the FILTER_VALIDATE_EMAIL constant used internally by the "filter_var()" PHP function only verifies whether or not the format of an email address is correct. So, if you need to implement more advanced features, such as looking for MX records in the DNS and checking to see if the supplied host is actually a working email server, you should consider adding this functionality on your own. And with this final example, we've come to the end of this tutorial. As you saw before, utilizing the "EmailValidator" class in an isolated fashion is a breeze. However, things will become really interesting when I show you how to use it as part of a more complex validation strategy. This topic will be discussed in the next article. Final thoughts In this fourth chapter of the series, I extended the functionality of the previous sample validation program by adding yet another strategy class to it. This new class was tasked with checking the validity of a supplied email address. With the incorporation of this modular component to the ones defined in preceding articles, you should now have a clear idea of how to inject them into the corresponding form helper class to assemble different validation strategies on the fly. But before I get to that point, it'd be useful to define at least one more strategy class that allows us to validate URLs in a simple way. This will be the topic that I plan to discuss in the upcoming tutorial of the series, so stay tuned for more!
blog comments powered by Disqus |
|
|
|
|
|
|
|