Autoload
Include the autoload with namespace in your project
1. Setup your psr-4 namespace and path mapping
We have to setup psr-4 autoload setting in the composer.json file.
{
"autoload": {
"psr-4": {
"CompanyName\\Common\\": "some/path/to/common/",
"CompanyName\\Customize\\": "other/path/to/customize/",
"CompanyName\\Other\\": "complicated/path/to/other/"
}
}
}
The psr-4 DOESN’T care about the namespace having to exactly match the path structure.
Even if we have the same namespace that begins with CompanyName, we still can map to a different path with the same namespace prefix.
| Namespace | path |
|---|---|
CompanyName\\Common\\ |
some/path/to/common/ |
CompanyName\\Customize\\ |
other/path/to/customize/ |
CompanyName\\Other\\ |
complicated/path/to/other/ |
After we set the namespace to the specific path that we want, then the composer will autoload the file depending on the namespace seting in the composer.json.
2. Generate autoload file
We can use the docker composer image to generate the autoload file in the vendor folder.
So go to the folder that includes the composer.json file, then run the following command to generate the vendor/autoload.php file
docker run --rm --interactive --tty \
--volume $PWD:/app \
composer dump-autoload
If your project needs to use the different composer version. You can specify the version name behind the docker composer image
docker run --rm --interactive --tty \
--volume $PWD:/app \
composer:1.9.3 dump-autoload
3. Include vendor/autoload.php file to your project
You can load the vendor/autoload.php, then the composer will help you to load every file depending on your psr-4 setting in the composer.json file
<?php
require_once __DIR__ . '/vendor/autoload.php';
Optimize autoload
The composer will look at all of your files inside the path that you set. So it might take a lot of time to search all files.
We can let composer search your all file first and pre-generate a file mapping array to optimize the loading speed.
docker run --rm --interactive --tty \
--volume $PWD:/app \
composer dump-autoload -o