Composer and autoload using your own classes
I haven't yet found a topline explainer of how the autoload function works in Composer, if you want to add a custom folder to composer's autoload function.
We're going to pretend we're using composer to autoload our project and run phpunit. My project will be called MyProject
. Here is my class:
<?php
namespace MyProject;
class MyClass {
}
?>
Firstly, let's add composer to this project:
composer require --dev phpunit/phpunit
We also want Composer to autoload our MyProject
class and to map the namespace to the correct folder in our project (e.g. src/
).
After we added phpunit as above you will then find a file called composer.json
in the top level of your project. Open it up and add an autoload section, with a nested psr-4
object.
{
"require-dev": {
"phpunit/phpunit": "^12.1"
},
"autoload": {
"psr-4": {
}
}
}
Inside the psr-4 object, we're going to create a key/value pair. This key-value pair maps the namespace declared in your class to a real folder in your project:
{"namespace\\" : "path/to/class"};
For example:
{
"require-dev": {
"phpunit/phpunit": "^12.1"
},
"autoload": {
"psr-4": {
"MyProject\\" : "src/MyProject/classes/"
}
}
}
Once Done, you need to dump the autoload folder, so composer can relink your namespace to the class folder:
composer dump-autoload
Enjoy!
Thomas -