Search code examples
phpcomposer-phppsr-4

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?


Solution

  • 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.