Autoloading PHP class files

Using spl_autoload_register to automatically load required files for classes upon object instantiation.

Submitted by Obsidian on 14 Jun 2009, 17:45

Okay, you may be wondering what exactly I mean by autoloading PHP class files. Not to worry, when I first learned about this too, I was confused also.

Here's a brief summary:

When you instantiate an object using a class that has not been defined, the autoloader function that is specified will then attempt to load the function using a previously set user-defined function.

Okay, so now you ought to understand what it does. But how can we use it?
It's quite simple. You assign the autoloader function at the start of your script after being sure to define the function, and then attempt to instantiate a class as an object.

Personally, I prefer using writing a simple class for my autoloader, which I'll include an example of below.

Code: Select all
<?php
/**
 * Failnet - Class autoloader
 * 
 * 
 * @author Obsidian
 * @copyright (c) 2009 - Obsidian
 * @license http://opensource.org/licenses/gpl-2.0.php | GNU Public License v2
 */
class failnet_autoload
{
    /**
     * Constructor
     */
    public function __construct() { }

    /**
     * Autoload callback for loading class files.
     *
     * @param string $class Class to load
     * @return void
     */
    public function load($class)
    {
        $class = substr(strstr($class, '_'), 1));
        include FAILNET_ROOT . 'includes' . DIRECTORY_SEPARATOR . str_replace('_', DIRECTORY_SEPARATOR, $class) . '.' . PHP_EXT;
    }

    /**
     * Registers an instance of this class as an autoloader.
     *
     * @return void
     */
    public static function register()
    {
        spl_autoload_register(array(new self, 'load'));
    }
}
 
?>

In a separate file I have defined the FAILNET_ROOT and PHP_EXT constants, just for the root path and PHP file extension in use.

Now, if we load a class that isn't yet defined, what this will now allow us to do (after we call failnet_autoload::register() to setup the autoload function) is load the file that it should be in, according to a simple method that we have instructed PHP to use. After the first underscore, the class name specifies where the file that contains the class is located within the includes directory. Each underscore after the first will be replaced by the directory separator for further organization.

A practical example of this is if I have a class named failnet_event_register (and if the class is not defined) it will attempt to include the file located at [root]/includes/event/register.php
This results in less include statements in your code, class files are loaded just in time when they're needed, and things go faster.
 

Changelog:

by Obsidian on 25 Jun 2009, 05:47: Let's make a few grammer fixes, shall we?

License:

All articles in the knowledge base are licensed under the phpbbmodders beerware license.

Back to category


Knowledge Base index
cron