Hooks & events

Hooks & events

Hooks are how plugins intervene in the work of the core and of other plugins without changing their code. They're implemented WordPress-style by the Celena\Core\Plugin\Hook class. There are two kinds: actions (side effects) and filters (value transformation).

Name contract: <area>.<event> in lowercase, e.g. news.published.

Actions

A side effect with no return value. There can be several subscribers; order doesn't matter.

use Celena\Core\Plugin\Hook;

// Subscribe:
Hook::on('news.published', function (array $news): void {
    // e.g. send a notification
});

// Fire (the core/module does this):
Hook::action('news.published', $news);

Filters

Transform a value, passing it down the chain of subscribers.

// Subscribe (priority optional, lower = earlier):
Hook::addFilter('news.title', fn (string $t) => trim($t), 10);

// Apply:
$title = Hook::filter('news.title', $news['title'], $news);

Built-in core hooks

HookTypeArguments
kernel.bootactionContainer $c
request.beforeactionRequest $req
response.before_sendfilterResponse $res, Request $req
user.registeredactionarray $user
user.login.successactionarray $user
user.login.failedactionstring $email, string $ip
news.publishedactionarray $news
news.titlefilterstring $title, array $news
template.render.beforeactionstring $template, array $vars
template.globalsfilterarray $vars
admin.sidebarfilterarray $items
admin.notificationsfilterarray $items
cache.clearedactionstring $type

The list grows as the core grows.

Common scenarios

Add an admin menu item

Hook::addFilter('admin.sidebar', function (array $items): array {
    $icon = new \Celena\Core\Template\Tags\IconTag();
    $items[] = [
        'svg'          => $icon(['name' => 'mail', 'size' => 22, 'class' => 'sb-ico']),
        'label'        => 'Leads',
        'url'          => '/admin/forms',
        'slug'         => 'forms',
        'active_slugs' => ['forms', 'leads'],
        'children'     => [
            ['label' => 'Forms',    'url' => '/admin/forms', 'slug' => 'forms'],
            ['label' => 'All leads', 'url' => '/admin/leads', 'slug' => 'leads'],
        ],
    ];
    return $items;
});

Pass a variable to all templates

Hook::addFilter('template.globals', function (array $vars): array {
    $vars['my_flag'] = '1';   // available as {my_flag} in any template
    return $vars;
}, 0);

Add a notification to the "bell"

Hook::addFilter('admin.notifications', function (array $items): array {
    $items[] = ['title' => 'New leads', 'text' => '3 items', 'url' => '/admin/forms', 'time' => ''];
    return $items;
});

Your own hooks in a plugin

A plugin can emit its own events so other extensions can subscribe:

Hook::action('shop.order.created', $order);
$price = Hook::filter('shop.price', $price, $product);

Document such hooks in your plugin's docs/hooks.md — it's the contract for integrations.