HomePHP Page 3 - Checking Email Addresses with the Strategy Design Pattern
Building a strategy class for validating email addresses - PHP
In this fourth part of a series on the strategy design pattern, I extend the functionality of the sample validation program by adding another strategy class to it. The new class will check the validity of a supplied email address.
As you may have guessed, defining a new strategy class that validates email addresses is very similar to creating components that check for integer and float numbers. The entire process is reduced to deriving a concrete subclass from the parent "AbstractValidator" and overriding its "$_filter" and "$_errorMessage" properties respectively. It's that simple, really.
The following code fragment shows the definition of the aforementioned subclass, not surprisingly called "EmailValidator":
class EmailValidator extends AbstractValidator
protected $_filter = FILTER_VALIDATE_EMAIL;
protected $_errorMessage = 'Please enter a valid email address.';
What can I say about the above "EmailValidator" class that hasn't already been said? Well, not much really, except for the fact that in this case it uses the FILTER_VALIDATE_EMAIL constant to determine whether or not a given email address is properly formatted. Since this PHP filter doe not also check to see if the domain part of the address is a valid host, or if it has an associated MX record in the DNS, adding this functionality is up to you. You've been warned.
Okay, having already defined a new strategy class that can be used for checking email addresses, the next logical step is to test it as a standalone component, so you can see for yourself how easy it is to put it in action.
But guess what? This will be done in the section to come. To get there, click on the link below and keep reading.