Each time you develop a Grav plugin, you are required to add a base plugin class structure, a simple php class which responds to one or more Grav events.

Usually a plugin does not require nothing more than the base plugin class, but other more complex plugins may implement a small library which lives inside the plugin itself.

This library lies on its own namespace and its not automatically autoloaded. This means you must manually require your library classes and this can be a pain when the library grows up.

It would be nice to find a way to autoload and automatically register your library classes, so you can use them by requiring their namespace.

To accomplish that task, we can rely on the Composer's ClassLoader object, implementing an autoload function in our base plugin class as follows:


use \Composer\Autoload\ClassLoader;

class MyClass {

    private $loader = null;

    protected function autoload($namespace, $folders)
        if ($this->loader === null) {
            $this->loader = new ClassLoader();

        $this->loader->setPsr4($namespace . '\\', $folders);

Next, to autoload your library, just call that function as follows:

$this->autoload([NAMESPACE], array(__DIR__ . '/classes'));

The ClassLoader will register the given NAMESPACE for your Psr4 library, which lives into the [Plugin]/classes folder.

If you want to check a real example, you can refer the Gravstrap plugin base class.

Next Post Previous Post

Related Posts