Search code examples
phpspl-autoload-register

PHP spl_autoload_register


I am trying to take advantage of autoloading in PHP. I have various classes in different directories, and so I have bootstrapped the autoloading as follows:

function autoload_services($class_name)
{
    $file = 'services/' . $class_name. '.php';
    if (file_exists($file))
    {
        require_once($file);
    }
}

function autoload_vos($class_name)
{
    $file = 'vos/' . $class_name. '.php';
    if (file_exists($file))
    {
        require_once($file);
    }
}

function autoload_printers($class_name)
{
    $file = 'printers' . $class_name. '.php';
    if (file_exists($file))
    {
        require_once($file);
    }
}

spl_autoload_register('autoload_services');
spl_autoload_register('autoload_vos');
spl_autoload_register('autoload_printers');

It all seems to work fine, but I just wanted to double check that this is indeed considered acceptable practise.


Solution

  • Sure, looks good. The only thing you might do is register them in the order they're most likely to hit. For example, if your most commonly used classes are in services, then vos, then printers, the order you have is perfect. This is because they're queued and called in-order, so you'll achieve slightly better performance by doing this.