Home arrow PHP arrow Page 3 - Using Multiple Strategy Classes with the Strategy Design Pattern

The Strategy pattern in action - PHP

Being one of the most popular contenders in the exciting, but very often complex, terrain of software design, the Strategy design pattern is a well-trusted paradigm. It allows you to build more flexible and efficient applications by appealing to the functionality of two of the big pillars of solid object-oriented programming: favoring Composition over Inheritance, and encapsulating the concepts that vary. This is the conclusion to a six-part series that shows you how to use the Strategy design pattern to validate incoming data.

TABLE OF CONTENTS:
  1. Using Multiple Strategy Classes with the Strategy Design Pattern
  2. Review: the example classes developed so far
  3. The Strategy pattern in action
  4. Setting up a different validation strategy
By: Alejandro Gervasio
Rating: starstarstarstarstar / 2
April 28, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Since the example that I'm about to show you will require using all of the classes shown previously, I'm going to define a basic autoloading class, which will save me from the hassle of including them manually. The autoloader will look like this:

<?php

class Autoloader

{

    private static $_instance;

   

    // get Singleton instance of the autoloader

    public static function getInstance()

    {

       if (!self::$_instance)

       {

           self::$_instance = new self;

       }

       return self::$_instance; 

    }

   

    // private constructor

    private function __construct()

    {

        spl_autoload_register(array($this, 'autoload')); 

    }

   

    // prevent cloning instance of the autoloader

    private function __clone(){}

   

    // autoload classes on demand

    public static function autoload($class)

    {

        $file = $class . '.php';

        if (!file_exists($file))

        {

            require_once 'FileNotFoundException.php';

            throw new FileNotFoundException('The file containing the requested class was not found.');

        }

        require $file;

        unset($file);

        if (!class_exists($class, false))

        {

            require_once 'ClassNotFoundException.php';

            throw new ClassNotFoundException('The requested class was not found.');

        }

    }  

}

<?php

(ClassNotFoundException.php)

class ClassNotFoundException extends Exception{}

That was easy to follow, right? Basically, all that the previous "Autoloader" class do is include classes on demand (AKA lazing loading) using the SPL "spl_autoload_register()" function. With the autoloader already set, it's time to create an example that shows how to validate a bunch of data according to a certain strategy. The script below does exactly that. Check it out: 

<?php

// include autoloader

require_once 'Autoloader.php';

$autoloader = Autoloader::getInstance();

// create an instance of the form helper

$formHelper = new FormHelper();

// add some validators to the form helper

$formHelper->addValidator(new IntegerValidator(10.5))

           ->addValidator(new FloatValidator(49.1))

           ->addValidator(new EmailValidator('bademailadress.com'))

           ->addValidator(new UrlValidator('http://www.devshed.com'));

// validate inputted data and display all error messages in one go

if (!$formHelper->validate())

{

    echo $formHelper->getErrorString();

      /*

    displays the following

    The value 10.5 is incorrect. Please enter an integer value.

    The value bademailadress.com is incorrect. Please enter a valid email address.

    */

}

else

{

    echo 'The submitted data is correct!';

}

As you can see, the above example implements at run time a validation strategy that requires checking first an integer value, then a float number and finally an email address and an URL. I don't want to sound too verbose, but this simple script shows in all its splendor the power of the Strategy pattern: on one hand, the objects responsible for checking the supplied data are loosely-coupled, easily interchangeable components (remember the great OOP commandment "Encapsulate the concept that varies"?), while on the other hand the functionality offered by the objects in question is employed by the form helper via Composition, not Inheritance. In this case, we get the best of both worlds.

What's more, the pattern implements a model so flexible that it makes it possible to "assemble" a whole new validation strategy by using fewer validator objects or even the same ones in a different sequence. To demonstrate how to accomplish this, in the last section of this tutorial I'm going to create another example, pretty similar to the previous one, which this time will implement a strategy that will permit us to validate only integers and email addresses.

So read the segment to come. It's only one click away.



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