Yahya Uddin
Yahya Uddin

Reputation: 28871

`$prepend` parameter in the Composer Class Loader

I am using the loader in Composer like so.

/** @var \Composer\Autoload\ClassLoader $loader */
$loader = require __DIR__ . '/vendor/dependencies/autoload.php';
$loader->add('MyAppNamespace', __DIR__, true);

As you can see the loader takes 3 parameters, which is documented here: https://getcomposer.org/apidoc/1.0.0/Composer/Autoload/ClassLoader.html#method_add .

I am extremely confused at to what the 3rd boolean parameter $prepend does. The link above says the $prepend means the following: Whether to prepend the directories. However I have no idea what this means.

Can someone please explain what the $prepend parameter does with an example.

Thanks!

Upvotes: 3

Views: 69

Answers (1)

michaJlS
michaJlS

Reputation: 2500

Have a look at composer code:

$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
    $this->prefixesPsr0[$first][$prefix] = (array) $paths;
    return;
}
if ($prepend) {
    $this->prefixesPsr0[$first][$prefix] = array_merge(
        (array) $paths,
        $this->prefixesPsr0[$first][$prefix]
    );
} else {
    $this->prefixesPsr0[$first][$prefix] = array_merge(
        $this->prefixesPsr0[$first][$prefix],
        (array) $paths
    );
}

As you can see, $prepend determines if paths provided by you (__DIR__) will be prepended or appended. Usually it doesn't matter, as you have only one path per namespace, but you could have more, and e.g. use this mechanism to override some class delivered with vendor lib by your own implementation.

Upvotes: 2

Related Questions