Composer autoload in Wordpress custom plugin

Viewed 1524

I'm developing a brand new Wordpress plugin and I would like to use Composer to autoload classes.

Here is the plugin directory heriarchy:

enter image description here

my composer.json content:

{
    "autoload": {
        "psr-4": {
            "G4S_ECommerce\\": "src"
        }
    }
}

In the directory where composer.json is, on cmd, I execute:

composer install -> this generates the vendor/composer folder and the vendore/autoload.php.

composer composer dumpautoload -o -> outputs "Generated optimized autoload files containing 0 classes"

In the main file G4S_Ecommerce.php I put the following line:

 require __DIR__.'/vendor/autoload.php';

In the same file I put

use G4S_Ecommerce\Includes\Ecommerce;

$starter = new Ecommerce();

but it leads me to a Fatal error: Uncaught Error: Class 'G4S_Ecommerce\Includes\Ecommerce' not found

Why the composer dumpautoload -o returns 0 classes? What am I doing wrong?

Thanks

1 Answers

First (it is not obvious from your files structure) you need to set a namespace for your Ecommerce class (i.e., G4S_Ecommerce/Includes)

Second, based on what you've declared in the autoload directive, composer is expecting to find the G4S_Ecommerce folder under the src folder, and in that folder you need to place your php class file with a name identical to the class name (i.e., Ecommerce).

Related