Home arrow PHP arrow Page 4 - Registry Classes in Action with Late Static Bindings in PHP 5.3

Including an autoloader class - PHP

In this second part of the series, I show you how useful late static bindings can be for dealing with a hierarchy of classes in static environments. In this case, the classes that compose that hierarchy are simple implementations of the registry design pattern, but this feature can be utilized in different situations and yield similar results.

TABLE OF CONTENTS:
  1. Registry Classes in Action with Late Static Bindings in PHP 5.3
  2. Review: definitions of previous registry classes
  3. The registry classes in action
  4. Including an autoloader class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
May 18, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As I said in the section that you just read, it’d be useful to add to the previous example an autoloader class that includes source classes on request, thus avoiding the hassle of loading them manually. So, here’s one that performs this task:

(Autoloader.php)

<?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.');

        }

    }  

}

( FileNotFoundException.php)

<?php

class FileNotFoundException extends Exception{}

(ClassNotFoundException.php)

<?php

class ClassNotFoundException extends Exception {}

Well, the above class features nothing especially interesting; it’s a simple wrapper for the built-in “spl_autoload_register()” PHP function, which loads source classes on demand. In this case, I made it a Singleton that registers itself in the SPL stack, but you can remove its “getInstance()” method or even implement it in a different way. It’s up to you.

Okay, now that the autoloader has been set, this is how it fits into the example coded before:

<?php

try

{

    require_once 'Autoloader.php';

    // grab the Singleton instance of the autoloader

    $autoloader = Autoloader::getInstance();

    // grab the Singleton instance of the ArrayRegistry class

    $arrayRegistry = ArrayRegistry::getInstance();

    // save some users to the registry

    $arrayRegistry->set('user1', 'Julie Smith')->set('user2', 'Mary Wilson');

    // get the first user from the registry

    echo $arrayRegistry->get('user1');

    /*

    displays the following

    Julie Smith

    */

}

catch (Exception $e)

{

    echo $e->getMessage();

    exit();

}

That looks much better, right? Considering that the functionality offered by late static bindings means that the creation of several registry classes that inherit from the abstract parent is a simple process, the inclusion of an autoloader makes a lot of sense here.

And speaking of different registry classes, what about defining a whole new registry class that gets and saves data to session variables? Since the “getInstance()” method is directly inherited from the base registry, implementing the additional methods would be a breeze. Don’t you want to face this small challenge? I bet you do!  

Final thoughts

That’s all for now. In this second part of the series, I provided you with a basic example that showed how useful late static bindings can be, specially when it comes to dealing with a hierarchy of classes in static environments. In this case, the classes that composed that hierarchy were simple implementations of the registry design pattern, but naturally this feature can be utilized in different situations and yield similar results.

Now, returning to the sample classes created before, it’s worth noting that the “getInstance()” method defined by the abstract registry uses the keyword “static” to determine what class has been called in a static context. It’s possible, however, to simplify the implementation of this method by using another handy function included with PHP 5.3 named “get_called_class().” Therefore, in the upcoming part of the series I’m going to take a closer look at this function, so you can learn how to use it.

Don’t miss the next tutorial!



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