👀 Get a glimpse of Kirby 5 Learn more
Skip to content

Plugin setup with autoloader

The basic plugin setup tutorial covered plugins with only an index.php file. But what if your plugin is built with several classes in separate files?

This tutorial is based on the basic plugin setup. You should be familiar with it before reading this tutorial.

The Pluginkit: Our example plugin

There is a Pluginkit example plugin with an autoloader as well. You can find its code in the 2-autoloader branch of the Pluginkit.

If you want to follow along, you can download a ZIP file of that branch or get it via Composer:

composer create-project getkirby/pluginkit site/plugins/your-plugin dev-2-autoloader --remove-vcs

About autoloaders

If your plugin uses PHP classes, you should use one PHP file per class to keep everything organized. Those files need to be loaded somehow.

The most efficient way to load PHP classes is to use an autoloader. It will dynamically load your PHP files once they are needed for the first time, which is great for performance.

How to use an autoloader in your plugins

Kirby ships with the F::loadClasses() method, which is a super simple class autoloader.

You can call it in your plugin's index.php with the list of your classes to load:

index.php
F::loadClasses([
    'superwoman\\superplugin\\superclass' => 'src/Superclass.php'
], __DIR__);

Once any of the autoloaded classes is first used, Kirby will automatically load its PHP file.