HomePHP Page 3 - Validating URLs with the Strategy Design Pattern
Validating URLs with the Strategy design pattern - PHP
In this penultimate part of the series, I will build a strategy class that validates URLs using the built-in PHP function “filter_var().” This process is similar to defining other strategy classes discussed in previous parts, so you shouldn’t have major difficulties understanding its underlying logic.
As you might have already guessed, building a strategy class capable of determining if an inputted value is a valid URL is a simple process. First, we derive a concrete subclass from the parent "AbstractValidator," and then we override the familiar "$_filter" and "$_errorMessage" protected properties.
This theory needs to be backed up with a functional example. So, the following code block shows the definition of this brand new strategy class, which in a blazing wave of creativity I called "UrlValidator." Here it is:
(UrlValidator.php)
<?php
class UrlValidator extends AbstractValidator
{
protected $_filter = FILTER_VALIDATE_URL;
protected $_errorMessage = 'Please enter a valid URL.';
}
If you were expecting to be confronted with a large portion of code, surely at this point you'll feel disappointed, as the definition of the "UrlValidator" is ridiculously short. Of course, this is somewhat tricky, since the class internally uses the FILTER_VALIDATE_URL constant to check the validity of a supplied URL, not to mention all of the functionality inherited from its abstract parent, which has been discussed in previous chapters of the series.
Having defined a strategy class that validates URLs, the next logical thing to do is to see if it really works as expected. Thus, in the section to come I'm going to build a trivial script that will put the class in action as a standalone component.
Want to see how this will be done? Then click on the link below and read the next few lines.