Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHP - Autoloading Methods

PHP

Composer Method

You dont need to necessarily register your own autoloader but use composer instead by adding an autoload section like so:

{
    "autoload": {
        "psr-4": {
            "Enums\\": "enums/",
            "Factories\\": "factories/",
            "Objects\\": "objects/",
            "Resources\\": "resources/"
        }
    },    
    "require": {
        "programster/core-libs": "^2.1",
    },
    "config": {
        "sort-packages": true,
        "platform" : {
            "php": "8.1.0",
            "ext-yaml": "1"
        }
    }
}

I need to investigate what this does performance wise.

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;

composer require irap/autoloader:1.0
# include composer for the autoloading package.
require_once(__DIR__ . '/vendor/autoload.php);

# Specify the directories that contain your classes 
# that you wish to autoload
$codeDirectories = [
    __DIR__,
    __DIR__ . "/enums",
    __DIR__ . "/factories",
];

new Autoloader($codeDirectories);

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