0

I've just begun using autoloader lazy loading in my app, and I'm running afoul of namespacing. The autoloader is trying to load things like new DateTime() and failing. Is there a trick to making my autoloader spcific to only my own namespaced classes?

Here is the code I have currently. I suspect it is a mess, but I'm not seeing just how to correct it:

<?php namespace RSCRM;
class Autoloader {
    static public function loader($className) {
        $filename = dirname(__FILE__) .'/'. str_replace("\\", '/', $className) . ".php";
        if (file_exists($filename)) {
            include_once($filename);
            if (class_exists($className)) {
                return TRUE;
            }
        }
        return FALSE;
    }
}
spl_autoload_register('\RSCRM\Autoloader::loader');

Happy to RTM if someone can point to a solid example.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
RSAdmin
  • 419
  • 1
  • 6
  • 20

1 Answers1

1

What I use is actually adapted from the autoloader used to Unit Test a few of the AuraPHP libraries:

<?php
spl_autoload_register(function ($class) {

    // a partial filename
    $part = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';

    // directories where we can find classes
    $dirs = array(
        __DIR__ . DIRECTORY_SEPARATOR . 'src',
        __DIR__ . DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR . 'src',
        __DIR__ . DIRECTORY_SEPARATOR . 'install' . DIRECTORY_SEPARATOR . 'src',
    );

    // go through the directories to find classes
    foreach ($dirs as $dir) {

        $file = $dir . DIRECTORY_SEPARATOR . $part;
        if (is_readable($file)) {
            require $file;
            return;
        }
    }
});

Just make sure the array of '$dirs' values point to the root of your namespaced code.

You can also take a look at the PSR-0 example implementation (http://www.php-fig.org/psr/psr-0/).

You might also want to look an into existing autoloader, like Aura.Autoload or the Symfony ClassLoader Component, although those might be overkill depending on what your requirements are.

I hope this helps.

Burnsy
  • 11
  • 2