Question

I'm trying to use the Composer ClassLoader. I'm trying to load up some CodeIgniter Libraries with PSR namespaces.

In my index.php I have:

$loader = include_once ROOTPATH . 'vendor/autoload.php';
$loader->add('CLI', ROOTPATH . 'application/libraries/CLI/');
$loader->register();

A simplified example of my folder structure is:

libaries/
    CLI/
        Tree/
            Parser.php     - namespace CLI\Tree;
    Settings.php           - namespace CLI;

Am I correct in assuming that Parser.php and Settings.php would be autoloaded? As I understood the documentation example it looks into sub-folders.

I want to avoid having to do the following:

$loader->addClassMap([
    'CLI\\Settings' => ROOTPATH . 'application/libraries/CLI/Settings.php',
    'CLI\\Tree\\Parser' => ROOTPATH . 'application/libraries/CLI/Tree/Parser.php',
]);
$loader->register();
Was it helpful?

Solution

Why don't you simply add the autoloading of your own code to the composer.json file you already have? That way Composer will create the autoloading file also for your own classes, you would be able to include your current project in another project without having to worry about autoloading (may be unlikely, but:), and you learn how to declare autoloading if you want to create your own modules.

From your code I guess this would work:

"autoload": {
    "psr-0": {
        "CLI": "application/libraries"
    }
}

Explanation: CLI is the prefix of the classes that could possibly found in the path. Make this as long as possible if you are using a lot of CLI classes, and only some are found in that path. Otherwise Composer will search a class in more than one directory, which is sort of bad for performance.

application/libraries is the prefix path where the PSR-0 style classes are located. PSR-0 dictates that a class named X_Y_Z or X\Y\Z is located in the path X/Y/Z.php, so the class prefix you were giving is NOT included in the prefix path you tell Composer to search for.

The prefix path is relative to the location of composer.json.

You could also use PSR-4. That would allow to remove empty directory structures, but will work only with namespaces:

"autoload": {
    "psr-4": {
        "CLI\\": "application/libraries/CLI"
    }
}

Two important differences: The class prefix must end with a backslash (and because this is JSON, the backslash has to be escaped, so double backslash).

Second: The class prefix will get removed from the path that is getting created from the classname. So a class W\X\Y\Z with the class prefix W\X\ will only create Y\Z.php as the path to the class and add the path prefix to it.

I added "CLI" to your path to show that PSR-4 would work, but that directory is not really needed in terms of PSR-4 - if it is empty, you could move files one level up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top