Depending on your directory structure you may have name spaced class files in different directories (that isn't really part of the structure, i.e. lib/ or core/).
Symfony ClassLoader is awesome, but I wanted something lightweight. That just solves the problem above, so inspired by other frameworks implementations I did this class.
Yes, it uses PSR-0.
I'd like some improvements on how I can get a better structure, use best practises and just make the class loader get as good as it can be.
<?php
namespace MyPro;
class Autoloader
{
/**
*
* @var array
*/
protected $directories = array();
public function loadClass($class)
{
if ($class[0] == '\\') {
$class = substr($class, 1);
}
$class = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $class). '.php';
foreach ($this->directories as $directory)
{
if (file_exists($path = $directory . DIRECTORY_SEPARATOR . $class))
{
require_once $path;
return true;
}
}
}
public function register()
{
spl_autoload_register(array($this, 'loadClass'));
}
public function addDirectories($directories)
{
$this->directories = (array) $directories;
}
public function getDirectories()
{
return $this->directories;
}
}
Example Use:
require_once __DIR__ . '/lib/MyPro/Autoloader.php';
$autoloader = new MyPro\Autoloader();
$autoloader->addDirectories(array(
__DIR__ . '/controllers',
__DIR__ . '/lib',
));
$autoloader->register();
Example Controller:
<?php
namespace Controller;
class Test extends MyPro\Controller
{
public function index()
{
echo 'hello!';
}
}
--- Is this correct use of namespaces (if you thinking this as some sort of framework)