Reference

Guide

Hooks

What are hooks?

Kirby fires a bunch of events when important things happen in the background. For example when a page is being created or deleted or a file gets uploaded. You can hook into those events and add your own functions that will be executed when those events happen.

Hooks are not restricted to Panel events, but are implemented everywhere: hooks are called no matter if an event happens in the Panel, on the command line or in your own scripts.

Available events

Registering hooks

Hooks can be registered in your config.php or in plugins

In your config

/site/config/config.php
return [
    'hooks' => [
        'page.delete:before' => function ($page) {
            // do something before a page gets deleted
        }
    ]
];

In a plugin

In a plugin, hooks are registered with the hooks extension. The extension accepts an array of key/value pairs where the key is the event and the value a function with the code that should be executed before or after an event.

Kirby::plugin('your/plugin', [
    'hooks' => [
        'page.delete:before' => function ($page) {
            // do something before a page gets deleted
        },
        'page.create:after' => function ($page) {
            // do something after the page was created
        }
    ]
]);

Accessing $kirby, $site and $user in a hook callback

You get full access to the current Kirby instance and its API with $this in a hook callback.

$kirby    = $this;
$site     = $this->site();
$user     = $this->user();
$username = $this->user()->username();
$role     = $this->user()->role();

Error Handling

You can now react on errors in a hook callback and return an error message.

Kirby::plugin('your/plugin', [
    'hooks' => [
        'page.update:after' => function ($newPage,$oldPage) {
            throw new Exception('Page Updated');
        },
        'page.create:after' => function ($page) {
            throw new Exception('Page Created');
        },
    ]
]);

Creating your own hooks

You can also define your own custom hook types in plugins, which works just like with the built-in hooks:

Kirby::plugin('your/plugin', [
    'hooks' => [
        'your-plugin.your-hook' => function ($page) {
            // do whatever you need
        },
    ]
]);

As you can see, only the name of the hook has changed. Please make sure to namespace your hooks by including the plugin name in the hook name. Otherwise your hooks might conflict with other plugins or future built-in hooks.

You can trigger your own hooks from anywhere in the system with the $kirby->trigger() and $kirby->apply() methods.