PSR4 autoloading classes for plugins

Instead of including classes in my own plugins:

like require_once __DIR__ . '/src/CheckScripts.php';

i load them with the main composer file.

index files are already autoloaded by Kirby.

With composer you can define the namespace that will be autoloaded following by the path.

Just add:

  "autoload": {
    "psr-4": {
      "Kirby\\Plugins\\": "site/plugins"
    }
  },

to your main composer file where you require “getkirby/cms”.

Create a folder with your plugin name example: Less

Filename: index.php

<?php
namespace Kirby\Plugins\Less;

use Kirby\Cms\App as Kirby;
use Kirby\Cms\Page;
use Kirby\Http\Header;

Kirby::plugin('Modufolio/Less', [

    'hooks' => [
        'page.*:*' => function ($page): void {
            $allModules = new AllModules();
            $allModules->writeModules();
            $allModules->compileLess();
        },
.....
.....

I don’t have to import Allmodules because it’s in the same namespace.

Filename: AllModules.php

<?php

namespace Kirby\Plugins\Less;

use Kirby\Toolkit\F;

class AllModules
{
    public function getModules(): array
    {
        $modulesArray = [];

        // find all sections templates and remove section- in the names
        foreach (site()->index()->filterBy('intendedTemplate', '*=', 'section_') as $page) {
....
....
1 Like

thanks for sharing. the idea to use the composer.json file of project to load all classes of installed plugins is nice.

what happens if you load classes that already have namespaces? like from a plugin of mine?

the psr4 loading worked well so far in most of my plugins. the plugin has their own composer.json file to do that. but i still had to add a manual load once in a while to fix certain issues with either non composer installs, plugin load order or hooks etc. i sadly i did not document why exactly but all my plugins that create a global helper function like janitor, autoid or monolog end up requiring the class non the less.

Plugins with other namespaces will still be loaded if the plug-in is in the plugin dir and your plugin has an index.php file.

If you want to autoload your classes without an fixed structure, maybe you can give robotloader a try.

I will research this later!

For some reason i couldnt get this working a few weeks ago in a plugin and ended up using the load helper

I’m not sure what the pros and cons are with both methods.

have you dumped the autoloader?
After setting up your namespaces in the composer.json file, afaik, you need to run this once:

composer dump-autoload