PHP – PSR-4: Autoloader

PSR-4 Autoloader is a php-fig specification for autoloading classes from file paths. Autoloaders remove the complexity of including files by mapping namespaces to file system paths.

Examples :

I recommand Composer to manage your autoload, but i will show you how to implement it by yourseft and with composer.

Summary

Your fully qualified class name must has this form :

NamespaceName\SubNamespaceNames\ClassName is located at : /NamespaceName/SubNamespaceNames/ClassName.php

Autoloader implementations MUST NOT throw exceptions, MUST NOT raise errors of any level, and SHOULD NOT return a value.

PSR-4 Autoload without composer

Project structure

How to PSR-4 Autoload without composer

Just put this lines in your bootstrap script (initialisation of your application) :

PSR-4 Autoload with composer

Project structure

How to PSR-4 Autoload with composer

Just put this lines in your bootstrap script (initialisation of your application) :

And create the composer.json like this :

Don’t forget to “composer update”

That’s all !