How to autoload your classes with composer

August 17, 2020

If you use composer and you don't want to require your classes in your project. You can autoload them like the classes from the packages.

To do that you add autoload in your composer.json file. If your class follows the psr-4 standard you can use psr-4 to include all classes in a folder, or else you can use classmap to include every class.

"autoload": {
"psr-4": {
"MyApp": "src/"
},
"classmap": [
"src/classes/MyClass.php"
]
}


Each time you make any chances on the composer.json run

composer dump-autoload


Your class file should include its namespace:

<?php

namespace MyApp;

class MyClass {
......


Optimizations you could do in autoloader:
https://getcomposer.org/doc/articles/autoloader-optimization.md