Page 1 of 1

Dynamically Loading Namespaced Classes

Posted: Fri Mar 25, 2011 8:31 pm
by gabriel1836
I'm working on a Data Mapper framework for PHP that will use Namespaces and rely exclusively on PHP5.3. In order to allow others to use the framework and extend its inner components as needed, I'd like to support a form of dynamic autoloading that will load the requested class file first from any custom namespaces and lastly from the framework namespace.

So far I have:

Code: Select all

class Gacela {

protected static $_instance;

protected $_namespaces = array();

protected $_sources = array();

protected $_mappers = array();

protected $_resources = array();

protected function __construct()
{
    spl_autoload_register(array(__CLASS__, 'autoload'));

    $this->registerNamespace('Gacela', dirname(realpath(__FILE__)));
}

protected function _findFile($file)
{
    if(file_exists($file) && is_readable($file)) {
        return true;
    }

    return false;
}

public static function autoload($class)
{
    $parts = explode("\\", $class);
    $self = self::instance();
    $return = false;

    if(isset($self->_namespaces[$parts[0]])) {
        $file = $self->_namespaces[$parts[0]].str_replace("\\", "/", $class).'.php';

        if($self->_findFile($file)) {
            $return = $class;
        }
    } else {

        $namespaces = array_reverse($self->_namespaces);

        foreach ($namespaces as $ns => $path) {
            $file = $path.$ns.str_replace("\\", "/", $class).'.php';

            if($self->_findFile($file)) {
                $return = $ns . $class;
                break;
            }
        }
    }

    require $file;

    return $return;
}

public static function instance()
{
    if(is_null(self::$_instance)) {
        self::$_instance = new Gacela();
    }

    return self::$_instance;
}
}
Unfortunately, it just goes to a white screen whenever I try to load any classes with it.

If you would like to see the full framework code, it can be downloaded from https://github.com/gabriel1836/gacela.

Can anyone provide insight on this could accomplished?