Introduction
There are commonly two methods to autoload files or classes in PHP. They are the spl_autoload-register function and the Composer approach. However, it is found that the spl_autoload_register has a hard time to resolve the paths to point to the correct files. Therefore, the Composer method is recommended.
A demo site using Composer is here.
Preparation
- Install the Composer package if not already done.
- Existing Composer can be updated to the latest version using the command:
- composer self-update
- To check installed version, run:
- composer -V
- Create the project folder structure as follows:
- project root folder
- inc
- Subfolder_1
- Class1_1.php
- other classes
- Subfolder_2
- Class2_1.php
- other classes
- Subfolder_1
- other_folders
- project_main.php
- composer.json
- inc
- project root folder
Steps
- Under the root folder, create composer.json. The “VendorName” is the top-level namespace and is mapped to the “inc” directory.
- To auto load non-classes files, use the “files” element to specify the locations of files for autoload.
{
"autoload": {
"psr-4": {
"VendorName\\": "inc/"
},
"files": [
"ajax_func/cpt_arch_lists-ajax.php",
"inc_a102702/constants.php"
]
}
}
- In class files, namespaces should follow the psr-4 recommendations to prefix with the top-level namespace.
- In project main.php, add the line:
require_once 'vendor/autoload.php';
- Using the terminal, cd to the project root folder and run the command:
composer dump-autoload- This will generate (or update) the ./vendor folder with the autoload.php inside it.
- Run the www-chxy.sh to modify the folders and files ownership and permissions.
- The autoload should work now.
Autoloader Optimization
Due to the way PSR-4 and PSR-0 autoloading rules are set up, Composer needs to check the filesystem before resolving a classname conclusively. This slows things down quite a bit, but it is convenient in development environments because when you add a new class it can immediately be discovered/used without having to rebuild the autoloader configuration.
The problem however is in production you generally want things to happen as fast as possible, as you can rebuild the configuration every time you deploy and new classes do not appear at random between deploys.
- You can optimize the autoloader by running this command in the Production environment:
- composer dump-autoload -o
Note: You should not enable any of these optimizations in development as they all will cause various problems when adding/removing classes. The performance gains are not worth the trouble in a development setting.
