Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

How to autoload vendor classes in a plugin?

Solved by Thomas Vantuycom View solution

Started by Thomas Vantuycom 6 years ago · 5 replies · 1566 views
6 years ago

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
<?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.

6 years ago

Your code looks OK.

What if you remove this line:

use Mollie\Api\MollieApiClient;

6 years ago

That does not work. Combinations I've tried:

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

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

6 years ago Solution

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

Suggested topics

Topic Participants Replies Views Activity
Plugins · by DrPen, 3 weeks ago
2 289 3 weeks ago
Plugins · by renedebaaij, 4 weeks ago
1 263 3 weeks ago
Plugins · by Thomas, 4 weeks ago
1 279 4 weeks ago
Plugins · by complanar, 2 months ago
6 600 1 month ago
Plugins · by BenLaKnet, 1 month ago
1 504 1 month ago