free-tech

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:
{
    "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"
        }
    }
}

Copy to clipboard
Copy

I need to investigate what this does performance wise.


Disadvantages


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

Copy to clipboard
Copy
# 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);

Copy to clipboard
Copy

Advantages


Disadvantages