0

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?

1

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

0

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:

  • Fast and robust
  • Flexibility (basically, you can use any naming convention you like)

Cons:

  • Needs to be re-run every time you add, remove or rename classes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.