Using PSR4-Autoloading via Composer vs spl_autoload_register


We’re building a new Slim application and we want to use PSR4-Autoloading with namespaces in our code.

We found two ways to do that, via Composer i.e.:

"autoload": {
    "psr-4": {
        "App\\Controller\\": "app/controllers",
        "App\\Middleware\\": "app/middleware",
        "App\\Model\\": "app/models"     

Or via spl_autoload_register i.e.:

spl_autoload_register(function ($class_name) {

  $filename = __DIR__ . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class_name) . '.php';
  require $filename;


What determines which method we should go with?


The version with spl_autoload_register could be faster, because it is directly suited to you. But because you are using Composer for autoloading your depenendecies, your version will be likely be as fast or even slower than the Composer implementation.

There is a principle called Don’t repeat yourself so why making something new, when the people from Composer already thought about it and implemented it.

That being said, Composer also uses spl_autoload_register internally

Conclusion: Use the Composer psr-4 autoload, its probably more robust than your implementation, and equally as fast performance-wise.

Answered By – jmattheis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published