How to autoload vendor classes in a plugin?

I scaffolded a plugin with devtools. The plugin’s main php file contains a line to autoload vendor classes, but I’m unsure how to call these classes in my plugin, resulting in a Class not found error.

I’m trying to use the Mollie API client like this:

<?php

namespace Grav\Plugin;

use Composer\Autoload\ClassLoader;
use Grav\Common\Plugin;
use Mollie\Api\MollieApiClient;

class MolliePlugin extends Plugin
{
    public static function getSubscribedEvents()
    {
        return [
            ['autoload', 100000],
            'onPluginsInitialized' => ['onPluginsInitialized', 0]
        ];
    }

    public function autoload(): ClassLoader
    {
        return require __DIR__ . '/vendor/autoload.php';
    }

    public function onPluginsInitialized()
    {
        if ($this->isAdmin()) {
            return;
        }

        $this->enable([
            'onFormProcessed' => ['onFormProcessed', 0]
        ]);
    }

    public function onFormProcessed($event)
    {
        $form = $event['form'];
        $action = $event['action'];

        switch ($action) {
            case 'mollie':
                $mollie = new MollieApiClient();
                // And so on
        }
    }
}

Class MollieApiClient cannot be found.

Your code looks OK.

What if you remove this line:

use Mollie\Api\MollieApiClient;

That does not work. Combinations I’ve tried:

use Mollie\Api\MollieApiClient;
$mollie = new MollieApiClient();
// Class 'Mollie\Api\MollieApiClient' not found
use \Mollie\Api\MollieApiClient;
$mollie = new MollieApiClient();
// Class 'Mollie\Api\MollieApiClient' not found
$mollie = new MollieApiClient();
// Class 'Grav\Plugin\MollieApiClient' not found
$mollie = new \MollieApiClient();
// Class 'MollieApiClient' not found
$mollie = new \Mollie\Api\MollieApiClient();
// Class 'Mollie\Api\MollieApiClient' not found
$mollie = new Mollie\Api\MollieApiClient();
// Class 'Grav\Plugin\Mollie\Api\MollieApiClient' not found

Did you use Composer from the command line while in the root directory of your own plugin? See Mollie API docs.

Yes, and Mollie sits in the vendor folder. That’s what puzzles me, it should work.

Found the problem: I was using an older version of the devtools plugin, which contained an error in the autoloading. Fixed with this change.

1 Like