Home arrow PHP arrow Page 2 - Checking Email Addresses with the Strategy Design Pattern

Review: validating input data with the Strategy design pattern - 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.

TABLE OF CONTENTS:
  1. Checking Email Addresses with the Strategy Design Pattern
  2. Review: validating input data with the Strategy design pattern
  3. Building a strategy class for validating email addresses
  4. The EmailValidator class as a standalone component
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
April 26, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Just in case you haven't read the previous installment of the series, where I added to the sample application a new strategy class that checked float numbers, below I listed for you all of the classes defined so far. This way you can study them in depth and quickly grasp their driving logic.

First, here's the form helper that accepts through its "addValidator()" method a configurable set of multiple validator objects at run time:

(FormHelper.php)

<?php

 

class FormHelper

{

    protected $_validators = array();

    protected $_errors = array();

   

    // add a validator

    public function addValidator(AbstractValidator $validator)

    {

        $this->_validators[] = $validator;

        return $this;

    }

   

    // get all the validators

    public function getValidators()

    {

        return !empty($this->_validators) ? $this->_validators : null;

    }

     

    // validate inputted data

    public function validate()

    {

        $validators = $this->getValidators();

        if (null !== $validators)

        {

            foreach ($validators as $validator)

            {

                if (!$validator->validate())

                {

                    $this->_errors[] = $validator->getFormattedError();

                }

            } 

        }

        return empty($this->_errors) ? true : false;

    }

   

    // get validation errors as an array

    public function getErrors()

    {

        return $this->_errors;

    }

   

    // get validation errors as a string

    public function getErrorString()

    {

        $errors = $this->getErrors();

        return !empty($errors) ? implode('', $errors) : '';

    }

   

    // clear state of the form helper

    public function clear()

    {

        $this->_validators = array();

        $this->_errors = array();

    }  

}

So far, so good. Now that you've surely understood how the above "FormHelper" class uses the injected dependencies to build and perform a predefined validation strategy, it's time to show the definition of the abstract validation class that encapsulates most of the functionality required by the distinct strategy subclasses. Here it is:  

(AbstractValidator.php)

 

<?php

 

abstract class AbstractValidator

{

    protected $_value = '';

    protected $_filter = '';

    protected $_options = null;

    protected $_errorMessage = '';

    protected $_errorPrefix = '<p>';

    protected $_errorSufix = '</p>';

   

    // constructor

    public function __construct($value, array $options = null)

    {

        $this->_value = $value;

        if (null !== $options)

        {

           $this->setOptions($options);

        }

    }

   

    // get supplied value

    public function getValue()

    {

        return $this->_value;

    }

   

    // set validation options

    public function setOptions(array $options)

    {

        if (empty($options))

        {

            throw new ValidatorException('Invalid options for the validator.');

        }

        $this->_options = $options;

    }

   

    // get validation options

    public function getOptions()

    {

        return $this->_options;

    }

     

    // set the validation filter

    public function setFilter($filter)

    {

        if (!is_string($filter))

        {

            throw new ValidatorException('Invalid filter for the validator.'); 

        }

        $this->_filter = $filter;

    }

   

    // get the validation filter

    public function getFilter()

    {

        return $this->_filter;

    }

   

    // set the error message

    public function setErrorMessage($errorMessage)

    {

        if (!is_string($errorMessage))

        {

            throw new ValidatorException('Invalid error message for the validator.');    

        }

        $this->_errorMessage = $errorMessage;

    }

   

    // get error message

    public function getErrorMessage()

    {

        return $this->_errorMessage;

    }

             

    // get formatted error string

    public function getFormattedError()

    {

        return $this->_errorPrefix . 'The value ' . $this->getValue() . ' is incorrect. ' . $this->getErrorMessage() . $this->_errorSufix;

    }

   

    // validate the supplied value 

    public function validate()

    {

        return filter_var($this->getValue(), $this->getFilter(), $this->getOptions());  

    }

}

(ValidatorException.php)

<?php

class ValidatorException extends Exception{}

As shown above, the "AbstractValidator" class is nothing but a simple a component that defines the generic behavior and metadata of concrete validation child classes. This obviously permits it to validate more specific types of data, including integer and float numbers, URLs and so forth. This is actually Inheritance 101, so I suggest that you pay attention to the following specific validator, which is charged with determining whether or not a supplied value is an integer:   

(IntegerValidator.php)

 

<?php

class IntegerValidator extends AbstractValidator

{

    protected $_filter = FILTER_VALIDATE_INT;

    protected $_errorMessage = 'Please enter an integer value.';

}

Definitely, the definition of the "IntegerValidator" subclass shows in a nutshell how easy it is to create refined implementations of its abstract parent to validate specific data types. Naturally, if you found it simple to grasp how this concrete class does its business, then understanding how the following one works will be a breeze. Take a look at it, please:  

(FloatValidator.php)

<?php

class FloatValidator extends AbstractValidator

{

    protected $_filter = FILTER_VALIDATE_FLOAT; 

    protected $_errorMessage = 'Please enter a float value.';

}

     

Mission accomplished, at least for now. At this stage, thanks to implementation of a couple of strategy classes, it's possible to provide the previous form helper (remember that one, right?) with the ability to validate integer and float numbers in a relatively simple fashion.

But wait a minute! If creating specific implementations of the base "AbstractValidator" class required us only to write a few lines of code, then it'd be really easy to take advantage of this situation and build yet another class that validates email addresses.

Well, that's exactly what I'm going to do in the following section. Therefore, to learn the full details regarding the definition of this brand new strategy class, click on the link below and read the lines to come.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 



© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap

Dev Shed Tutorial Topics: