Home arrow PHP arrow Page 3 - Checking Integers with the Strategy Design Pattern

Creating an abstract validation class - PHP

If you’re a PHP developer who wants to learn how to implement the Strategy design pattern in a real-world project, then you might want to take a look at this article series. Over the course of its six tutorials, you’ll walk through the development of a modular and flexible application, which will use this powerful pattern to validate different types of data, including integer and float numbers, email addresses and URLs.

TABLE OF CONTENTS:
  1. Checking Integers with the Strategy Design Pattern
  2. Review: implementing the Strategy design pattern to validate input data
  3. Creating an abstract validation class
  4. Validating integer numbers
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
April 20, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Put in a simple way, the abstract validator that I plan to build here will rely heavily on PHP filters. Such filters are very useful for validating different data types in a painless fashion. With this abstract class seated on top of the hierarchy, creating refined child validators that check integers, email addresses and URLs will be a breeze.

Having said that, it’s time to show the definition of the abstract validator. That’s exactly what the following code fragment does. Check it out:

(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{}

From the above code sample, it’s easy to understand how the “AbstractValidator” class works. It takes as an input argument the value to be checked via the constructor, and performs the actual verification process by using its “validate()” method, which is a proxy for the “filter_var()” built-in PHP function. The rest of the methods are pretty self explanatory; they allow you to set, format and get error messages, and assign additional options for a specific PHP filter. For obvious reasons the abstract validator doesn’t set a default filter to validate a supplied value, as this should be specified by the subclasses derived from it.

So far, so good. Now that you've grasped the logic driving this generic validator, at this point you should have a clearer idea of how this class fits into the schema imposed by the Strategy pattern. In reality, refined implementations of the abstract validator will be “strategy” classes that can be inputted directly into another class, such as the helper defined in the previous tutorial.

You'll understand this concept better when I start creating some of those strategy classes, which will be responsible for checking predefined data types. Keeping this idea in mind, in the last segment I’m going to derive the first of these concrete validators. It will be tasked with checking whether or not a supplied value is an integer.

As usual, to see how this refined validator will be defined, click on the link below and read the lines to come.      



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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

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

 


Dev Shed Tutorial Topics: