This is my current autoLoader:
function classAutoLoad($class) {
if (file_exists($_SERVER['DOCUMENT_ROOT']."/framework/includes/class/$class.class.php"))
include($_SERVER['DOCUMENT_ROOT']."/framework/includes/class/".$class.".class.php");
}
spl_autoload_register('classAutoload');
Usage:
$class = new Classname;
Basically it will load all classes inside /class/, not including directories. What I am trying to do is, be more clean.
I have a lot of classes, and I want to package them into directories.
How can I enable support for packages here? Or is there a popular library for this?
You have to come up with some way of mapping class names to files. You can do this explicitly by maintaining an associative array or your can use some convention like PSR-0. PSR-0 states that namespaces should translate to directories in the $class
that gets passed to your autoloader, so you can replace the namespace sepratator \
by the directory separator of your system.
Your code seems to be better decent for what you're trying to do, loading in one specific directory. However, I would change the if (file_exists(...)) { ... }
to trigger an error if the file doesn't exist. Something like
if (file_exists(...)) {
...
} else {
throw new RuntimeException($class . ' could not be found.');
}
You can take a look at Loader.php which is the autoloader script that I use. This takes into account namespaces and can be modified to only look at *.class.php
.
To use it:
require_once($_SERVER['DOCUMENT_ROOT']."/path/to/Utilities/Loader.php");
\Utilities\Loader::register();
$class = \Namespace\ClassName();
If the autoloader does not have to be fully dynamic, you can simly use PHP Autoload Builder. It scans your entire directory and automatically creates a static class-to-filename mapping that looks roughly like this:
spl_autoload_register(function($class) {
static $classes = null;
if ($classes === null) {
$classes = array(
'my\\first\\class' => 'My/First/Class.php',
'my\\secondclass' => 'My/SecondClass.php'
);
}
$cn = strtolower($class);
if (isset($classes[$cn])) {
require __DIR__ . $classes[$cn];
}
});
Pros:
Cons: