Home arrow PHP arrow Page 2 - Verifying Float Values with the Strategy Design Pattern

Review: the sample classes developed so far - PHP

In this third part of a series on validating incoming data with the strategy design pattern, I create a brand new strategy class that can check whether or not a supplied input value is a float number. The addition of this class extends the capabilities of the sample validation program that I’m building in this series.

TABLE OF CONTENTS:
  1. Verifying Float Values with the Strategy Design Pattern
  2. Review: the sample classes developed so far
  3. Adding a strategy class for checking float numbers
  4. Using the FloatValidator class as a standalone component
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
April 21, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As usual, before I get my hands dirty defining a brand new strategy class responsible for validating float numbers, first I’d like to spend a few moments reintroducing all of the sample classes developed so far in this series. This way you can analyze them in more detail and understand more clearly how they fit with each other.

Having said that, here’s the definition of a simple form helper. It accepts different strategy classes via its “addValidator()” method. This permits it to validate distinct types of data with minor hassles. Take a look at it, please: 

(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();

    }  

}

As I said before, the previous form helper relies on the benefits offered by Composition to inject a bunch of data checking classes from the outside, which can be used to easily assemble different validation strategies at run time.

Since the source code of this helper is pretty easy to follow, I suggest you move on and look at the definition of the following abstract validator. It encapsulates the common structure and logic of a generic validation (read strategy) class. 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{}

From the above code fragment, it’s clear to see how this abstract validation class does its thing. It simply uses the functionality provided by PHP filters to validate an inputted value, previously stored on the protected “$_value” property. Not surprisingly, the workhorse method of this class is called “validate()” and is responsible for checking whether or not the mentioned value is valid.

This abstract structure encapsulates a lot of generic logic and is accommodated comfortably on top of the hierarchy. Therefore, defining refined implementations of it, which can be used to check different types of data, such as integer numbers, is as simple as creating the following subclass: 

(IntegerValidator.php)

<?php

class IntegerValidator extends AbstractValidator

{

    protected $_filter = FILTER_VALIDATE_INT;

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

}

That was simple to code and read, wasn’t it? By simply overriding the “$_filter” and $_errorMessage” properties declared by the abstract validator that you just saw, it’s possible to create a custom validation class in the blink of the eye. This class can be injected either as a strategy object into the previous form helper or used as a standalone component.

However, as I explained in the introduction, my goal here is to progressively build a modular program aimed at checking incoming data by using different strategy classes. Obviously, in its current state this sample program is capable of validating only integers, which isn’t very useful. So, it’s time to add a brand new strategy class to it that permits it to check whether or not a supplied value is a float number.

The full details regarding the definition of this class will be shown in the following section. Thus, to learn more, click on the link below and keep reading.



 
 
>>> 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: