2
votes

I'm using composer in a legacy project that have lots of classes with no namespace. Refactoring is not an option (it's a very huge application), but all new modules are fully psr-4 compliant. The legacy code has it's own autoload method (using a class map, pretty efficient).

My problem is: no matter in which order I add the autoloader methods, composer autoloader ALWAYS COMES FIRST! This is slowing down the load of each single class: every time I call a class from the legacy code, it first tries to match it against all composer autoload options (including the findFileWithExtension() ), and only then it calls the alternative autoloader.

I've inspected it using PHPStorm+XDebug, and no matter which autoloader I include first, Composer autoload is always called before the legacy one.

Is there a way to change this behaviour??

Thanks in advance!!

3

3 Answers

5
votes

Ok, guys, I found the solution and want to share it with you: the spl_autoload_register() function has a third parameter: $prepend. When set to true, it will prepend the autoload function to the autoload queue, instead of appending it (it's actually documented at the official PHP Documentation). Composer always sets it to true, so that its autoloader is always called first. To fix it, I changed the legacy autoloader, setting $prepend to true, and called it AFTER including composer's autoload.

Hope it helps someone! :)

0
votes

Pass true as a third argument to the spl_autoload_register:

spl_autoload_register(your_autoload_func(), true, true);
0
votes

You need to be aware that composer use different ways to include php files, check vendor/composer/autoload_real.php for details, and remember that composer can include files directly in the place where you include

require_once('vendor' . DIRECTORY_SEPARATOR . 'autoload.php');

so if you are lucky to have vendor/composer/autoload_static.php remember that adding $prepend parameter to your own spl_autoload_register() may not be enough.