Autoloading 101

For some who are new to PHP 5 you may have heard about a PHP feature calledĀ SPL Autoload or Autoloading classes.

Ordinarily, when you write a class your code may look something like this:

<?php

require_once('../code/foo.php');
require_once('../code/baz.php');

class widget extends foo
{
    public function event()
    {
        $baz = new baz();
    }
}

Autoloading does away with the need to put require / include once to include class file by enabling you to attach a function that performs an action before a class is instantiated. SPL autoload works when you try to instantiate a class or use reflection on a class and only works when the class hasn’t already been loaded.

Basic Autoloader

This Autoload script looks at the name of the class, converts the class name into a path then includes the file. In this example, I’ve written my function so it will handle PHP 5.3 namespaced classes as well.

The Autoload function works on a couple of assumptions:

  1. There is only one class per file,
  2. Your library directories are organised by a vendor structure

This is a fairly high level implementation, there are a number of different approaches to class loading in PHP 5 however, this is my favourite because it’s the simplest.

<php

// Register autoloader
spl_autoload_register('loadGenericClass');

// Set base include paths
$paths = array();
$paths[] = "/PATH/TO/LIBRARY/";
$paths[] = "/PATH/TO/ANOTHER_LIBRARY/";
$paths[] = get_include_path();

set_include_path(implode(PATH_SEPARATOR, $paths));

// Autoloader
function loadGenericClass($class)
{
    $path = str_replace(array('_', '\\'), '/', $class) . '.php';

    @include_once($path);
}

Stepping through the code

The first part registers a function that can be used to include a file. In this instance, the function is called loadGenericClass. Underneath, I’ve set up an array of paths to search through. We’re going to add these to the include path since we want our autoload function to have complete access to our bespoke code and PEAR / PECL classes. In my example, my library files are in multiple locations which is I why I prefer to use an array over building a long string.

When PHP calls the loadGenericClass function it passes in the class name. In this instance, I’m performing a simple replace to look for underscores (_) and backticks (\) and replace them with a slash. The slash represents the path of the class file. For example Vendor_Group_Class is converted to Vendor/Group/Class.php.

We also look for backticks because in PHP 5.3 now has namespace support. In this instance, theĀ variable will be \Vendor\Group\Class which is converted to Vendor/Group/Class.php.

Finally, the file gets included into the script. This will use the include path to load the class file.

And there you have it. Class loading in PHP 5 without the need for include and require everywhere.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>