PHP - Autoloading Methods
Composer Method
You dont need to necessarily register your own autoloader
but use composer instead by adding an autoload
section like so:
Disadvantages
- Requires you to add
namespace xxx
to all your files that you wish to autoload. - I was unable to figure out a way to have any classes autload from the root level. Hence, all files at this level had to either be manually included, or moved into a namespaced subfolder.
- Need to run
composer dump-autoload
Simple Autoloader Package
There is a package to simplify autoloading for you. All you need to is include it, and pass the autoloader a list of directory paths that contain your classes that
have a filename that matches their class name. E.g. MyClass.php
for class MyClass
;
Advantages
- Don't need to use namespaces on your code files.
- Works with files being int the top/root level.
Disadvantages
- With large codebases, this might decrease performance, since the code will search through all the files across all the specified folders for the file with the appropriate name.
- Every time you add a new code folder you need to remember to add the path to your autoloader directories.
References
Last updated: 16th August 2022
First published: 16th August 2022
First published: 16th August 2022