Use composer to load custom classes [closed]

Without more context from you, I can only assume and show you what I have done that works for me using PSR4 Autoloading.

Example:

Assuming that all my custom class directories and files is in ./inc folder

In your composer.json, add this

"autoload": {
    "psr-4": {
        "Inc\\": "./inc"  
    }
}

Inc is the vendor name of your application, use this for namspacing files inside your inc directory like namespace Inc/Api;

./inc is the directory(with all the class files or nested directory) you want to autoload.

Next, do this in your terminal to generate the vendor directory & autoload the files.

composer dump-autoload

Lastly, require the the autoloading by adding this to your plugin file eg. my-awesome-plugin.php

if (file_exists(dirname(__FILE__) . '/vendor/autoload.php')) {
    require_once dirname(__FILE__) . '/vendor/autoload.php';
}

Leave a Comment