Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Plugins

How to autoload vendor classes in a plugin?

Solved by Thomas Vantuycom View solution

Started by Thomas Vantuycom 6 years ago · 5 replies · 1076 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 Rene, 1 week ago
2 42 1 week ago
Plugins · by Xavier, 4 weeks ago
2 53 4 weeks ago
Plugins · by Luka Prinčič, 7 years ago
3 1179 1 month ago
Plugins · by Sebastian van de Meer, 1 month ago
1 47 1 month ago
Plugins · by PIERROT Alain, 2 months ago
3 71 2 months ago