Hooks: callbacks, filters and payloads

Handbook · Coverage · Code reference

A hook is a named point where code calls registered PHP callbacks. It lets a plugin react to something or change a value without editing the caller. A callback is an ordinary closure: function ($payload) { ... }.

Read plugins for loading hooks.php. Read testing before testing callbacks that write data.

Access the service

HookServiceProvider registers one HookService under the container key hook and aliases its class to that binding. These resolve the same service:

$hooks = app('hook');
$hooks = app(\App\Core\Services\HookService::class);

App\Facades\Hook forwards static calls to that binding:

use App\Facades\Hook;

Hook::addAction('my-plugin.completed', function (array $payload): void {
    logger()->info('Completed', ['operation_id' => $payload['operation_id']]);
});

Registration stores a closure. It does not run the closure. Dispatch is the separate call that supplies its payload. Names are case-sensitive strings. There is no requirement to define a schema before registering or dispatching.

Complete registration and dispatch API

All methods below are public methods of HookService. Defaults are literal source defaults. mixed means the service does not enforce a particular PHP type.

Signature Result and behavior
register(string $hookName, Closure $callback, int $priority = 10): void Append callback; higher priority runs first
addAction(string $hookName, Closure $callback, int $priority = 10): void Alias of register
addFilter(string $hookName, Closure $callback, int $priority = 10): void Alias of register
run(string $hookName, mixed $data = null, bool $returnSingle = false): mixed Collect results or chain a filtered value
action(string $hookName, mixed $data = null): array Run callbacks against the same payload; collect non-null returns
actionStrict(string $hookName, mixed $data = null): array Synchronous action with propagated exceptions and no circuit-breaker skipping; caller owns the transaction
removeCallbacks(string $hookName): void Remove every callback registered for this name
filter(string $hookName, mixed $value): mixed Pass each non-null return to the next callback
veto(string $hookName, mixed $value, mixed $onFailure): mixed Like filter, but returns $onFailure as soon as a callback throws or is circuit-skipped. Use it for every allow/deny gate
call(string $hookName, mixed $data = null): mixed Filter when data is non-null; action when it is null
fire(string $hookName, mixed $data = null): array Alias of action
dispatch(string $hookName, mixed $data = null): array Alias of action

Use action and filter explicitly in new code. call('name', []) is a filter, while call('name') collects action results. That difference is easy to miss. doAction and applyFilters are not implemented methods.

Registration accepts Closure, not every possible PHP callable. Convert another callable using Closure::fromCallable(...) if needed. Registering the same closure object twice at the same priority is deduplicated. Different closure objects or priorities remain separate registrations.

When registering a combat.* name in an active PluginContext, registration checks the combat.hooks capability and may throw PluginPermissionException.

Each listener runs in the PluginContext of the plugin that registered it. Listeners registered from a plugin's register(), boot() or hooks.php are attributed to that plugin (HookService::registeringFor); listeners registered by core run as core even when a plugin route fires the hook. A listener that calls a protected API, such as an EconomyService credit, needs that permission in its own plugin's manifest. See security for capability boundaries.

Action example: one payload, several listeners

Place this in a plugin's hooks.php:

<?php

app('hook')->addAction('journal.entry.created', function (array $payload): string {
    return 'indexed:'.$payload['entry_id'];
}, 20);

app('hook')->addAction('journal.entry.created', function (array $payload): string {
    return 'announced:'.$payload['entry_id'];
}, 10);

In the controller/service that successfully creates the entry:

$results = app('hook')->action('journal.entry.created', ['entry_id' => 42]);
// ['indexed:42', 'announced:42']

Both listeners receive ['entry_id' => 42]. The first listener's return does not replace the second listener's input. A void callback contributes no result. Dispatching an unregistered action returns [].

For persistent side effects, dispatch at the correct transaction boundary and make listeners idempotent. The hook engine itself supplies no transaction, retry queue, deduplication key, or durable event delivery.

Filter example: each return becomes the next input

This example can run in an isolated test using a new service instance:

$hooks = new \App\Core\Services\HookService;
$hooks->addFilter('journal.limit', fn (int $limit): int => $limit * 2, 20);
$hooks->addFilter('journal.limit', fn (int $limit): int => $limit + 5, 10);

$result = $hooks->filter('journal.limit', 10);
// 25: double first, then add five.

Returning null leaves the current filter value unchanged. Returning false, 0, '' or [] replaces it. An unregistered filter returns its input. A filter callback can change the type; downstream code must decide whether that is acceptable. Keep your callback's return type aligned with the caller.

Priorities sort descending, unlike systems where smaller numbers run first. Avoid relying on ordering between unrelated callbacks with equal priorities. Ordering is evaluated lazily when the name is dispatched.

A working core filter: admin navigation

AdminSidebarService builds core sections and calls filter('admin.sidebar', $coreSections). The payload is the sections array itself, not ['sections' => ...] and not a User object.

In hooks.php, a defensive modifier can annotate an existing item:

<?php

app('hook')->addFilter('admin.sidebar', function (array $sections): array {
    foreach ($sections as &$section) {
        foreach ($section['children'] ?? [] as $index => $child) {
            if (($child['path'] ?? $child['route'] ?? null) === '/marketplace') {
                $section['children'][$index]['label'] = 'Plugin marketplace';
            }
        }
    }
    unset($section);

    return $sections;
});

Expected result: existing Marketplace children have the new label. This does not create an extra route or grant access to it. Match both path and route when checking existing entries because downstream providers can use either.

Individual hook references

The per-hook directory gives every current registry/dispatch name its own page. Each identifies whether core actually calls it, the real payload and return behaviour, examples and timing/failure limits. Catalogue-only names explicitly have no automatic integration.

Verified dispatch catalogue

The following are actual dispatch calls in backend/app/Core at the time this chapter was checked. A custom plugin can add its own dispatchers independently.

Hook Caller Kind Actual payload / use
user.created Core/Models/User.php, model created callback Action ['user' => $user]; newly persisted core User
admin.sidebar Core/Admin/AdminSidebarService.php Filter Core sections array directly; returned sections become menu
admin.dashboard.widgets Core/Http/Controllers/Admin/DashboardStatsController.php Filter []; returned value becomes dashboard widgets
pulse.tick, pulse.minute, pulse.hourly, pulse.daily Core/Services/PulseService.php, dynamic run("pulse.{$interval}", $context) Action-style run Context array directly: interval, timestamp, iso, minute, hour, day.
player.activity Core/Services/PlayerActivityService.php, record() actionStrict Activity event array; see player activity
player.activity.types Core/Services/PlayerActivityService.php, types() collect ['user' => ?User]; providers return activity type lists

For user.created, listen with function (array $payload) and read $payload['user']. Do not assume a registration endpoint is the only creator: Eloquent's created callback also runs for other normal model creation paths. Direct SQL inserts do not run Eloquent model events.

The admin.dashboard.widgets declaration in HookRegistry describes a widgets field, but its real dispatcher passes an empty array directly. Follow the dispatcher when writing a listener; schema metadata is not runtime wrapping.

moduleLoad, customMenus, alterModuleData, alterTemplateData, beforeUserAction and afterUserAction have default registrations in HookServiceProvider. This establishes callbacks, not live module lifecycle integration. No core dispatcher for these names was verified. Do not rely on these names to intercept page loading without an actual caller.

The pulse hook names above are dispatched when PulseService::executePulse() processes that interval. Scheduled processing needs the scheduler and the ticks queue worker; a synchronous local pulse:run --interval=minute --sync also dispatches the minute hook. The hook payload is distinct from the pulse.tick WebSocket heartbeat payload, which is broadcast for each processed interval.

Core also fires lifecycle actions through CoreEvents::afterCommit(), after the surrounding transaction commits: user.login, user.banned, user.unbanned, user.deleted, plugin.installed, settings.updated and antimulti.fingerprint_recorded and auth.logout (fired as a player signs out). They are notifications: a failing listener cannot undo the operation. Refusing a sign-in or registration is the job of the auth.allow_login filter, which fails open. A plugin that wants to receive appeals from banned players uses the auth.banned_login and auth.ban_appeal filters.

The registry also lists other auth, navigation and plugin lifecycle names. Do not assume those fire because their names appear in a catalog. Check the caller or add an explicit dispatcher in your own extension. Plugin lifecycle methods are explained separately in plugins.

Player activity hooks

player.activity lets a game plugin say "this player did something" without knowing who cares. Achievements, quests or leaderboards listen and react. Both names below are defined as experimental in HookServiceProvider.

Emit an activity

Call App\Core\Services\PlayerActivityService::record() from plugin code, inside the transaction that makes the activity true:

use App\Core\Services\PlayerActivityService;
use Illuminate\Support\Facades\DB;

DB::transaction(function () use ($user, $battle) {
    $battle->update(['result' => 'won']);

    if (class_exists(PlayerActivityService::class)) { // engines older than this hook
        app(PlayerActivityService::class)->record(
            $user,          // User model or positive user ID
            'battle.won',   // local key; core prefixes your plugin slug
            1,              // amount, 1 to 1,000,000
            (string) $battle->id, // source ID: repeat it and nothing happens
            ['stage' => $battle->stage], // optional, at most 16 scalar or null values
        );
    }
});

The full signature is record(User|int $user, string $key, int $amount, string $sourceId, array $metadata = [], ?DateTimeInterface $at = null): bool.

Argument Rule
$key 1 to 4 dot-separated segments matching ^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*){0,3}$, at most 32 characters; with the plugin prefix at most 64
$amount Integer from 1 to 1,000,000
$sourceId 1 to 100 bytes of UTF-8 text without control characters
$metadata At most 16 entries; string keys of 1 to 32 characters; values scalar or null
$at When it happened; defaults to now; sent to listeners in UTC

A broken rule throws InvalidArgumentException before anything is written or dispatched. Calling record() without an active plugin context (core code, or PluginContext::runAsCore()) throws LogicException. Plugin HTTP routes and hook listeners already run in their plugin's context; console commands and jobs need PluginContext::run('your-plugin', ...).

Core takes the plugin from PluginContext::active() and prefixes it: arena emitting battle.won produces arena.battle.won. A plugin cannot emit for another plugin: other.battle.won from arena becomes arena.other.battle.won.

Exactly once, inside your transaction

Each (player, full key, source ID) is delivered once. Core inserts a row into player_activity_receipts with insertOrIgnore; its unique index on user_id, activity_key and source_id is the guard.

Situation record() result
First time, listeners registered Receipt written, listeners run, returns true
Same player, key and source again Returns false; no listener runs
No listener registered Returns true; nothing is written
A listener throws The exception propagates out of record()

The receipt insert and the listeners run inside DB::transaction. When you already have a transaction, that becomes a savepoint in yours. Listeners are dispatched with actionStrict, so they are not wrapped in the usual try/catch and are never skipped by a circuit breaker. A listener exception therefore rolls back the receipt, every listener's writes and, once it reaches your outer transaction, your own writes. If your transaction rolls back for any other reason, the receipt goes too, and retrying the same source ID delivers it again.

Because nothing is written when no listener exists, an activity emitted before a listener plugin was enabled is not replayed later.

The exactly-once window (plugin authors)

Receipts are not kept forever. PlayerActivityService::pruneReceipts() deletes receipts older than core.activity_receipt_days (env PULSE_ACTIVITY_RECEIPT_DAYS, default 90, minimum 1), and the scheduled command pulse:activity-receipts:prune runs it daily at 03:20. So "once" means once inside that window:

  • A retry with the same player, key and source ID inside the window returns false; no listener runs.
  • After the receipt is pruned, the same report is delivered again as a first time. Listeners run a second time.

Example: a plugin reports arena.battle.won with source ID battle-4411 on day 1. A retry on day 30 is refused. A retry on day 120 is delivered again, and a quest listener counts the win twice.

So do not retry or replay reports older than the window, or give every report a source ID that is never reused (a database row ID or a UUID, not a counter that restarts). If your retry horizon is longer than 90 days, raise PULSE_ACTIVITY_RECEIPT_DAYS on the host.

A plugin that replays activity older than the window (a backfill, a re-dispatch of old events) must keep its own idempotency key for what it has already delivered; core's receipts no longer remember it. No first-party package replays activity today (checked 13 November 2026).

Listen for activity

The listener receives one array:

app('hook')->addAction('player.activity', function (array $event): void {
    // $event = [
    //     'user_id' => 12,
    //     'key' => 'arena.battle.won',
    //     'plugin' => 'arena',
    //     'amount' => 1,
    //     'source_id' => '981',
    //     'occurred_at' => '2026-11-07T10:11:12Z',
    //     'metadata' => ['stage' => 4],
    // ];
    if ($event['key'] !== 'arena.battle.won') {
        return; // not applicable: return, never throw
    }

    // Update your own rows here.
});

Each listener runs in its own plugin's context, not the emitter's, so any protected API it calls needs that permission in its own manifest. Follow these rules because a listener runs inside someone else's transaction:

  • Return quietly for activity that does not apply to you. Throw only when your own write genuinely failed and the whole operation should roll back.
  • Lock rows in a consistent order: the player's users row first if you need it, then your own rows. Never lock another plugin's rows.
  • Never create player_stats rows. Read them without getOrCreateForUser, firstOrCreate or EconomyService::balance(), which create a row with starting cash.
  • Keep work short and in the database. Queue broadcasts, mail or HTTP calls with DB::afterCommit().

Activity type catalogue

player.activity.types lets editors such as a quest or achievement admin list the keys enabled plugins can emit. PlayerActivityService::types(?User $user = null) calls HookService::collect('player.activity.types', ['user' => $user]). Each provider returns a list:

app('hook')->addAction('player.activity.types', fn (array $payload): array => [
    ['key' => 'battle.won', 'label' => 'Battles won', 'unit' => 'wins',
        'href' => '/battle', 'action_label' => 'Fight'],
]);
Field Rule
key Same local key rule as record(); core prefixes the provider's plugin
label Required plain text, 1 to 32 characters
unit Optional plain text, up to 16 characters
href Optional same-origin path starting with a single /, up to 255 characters
action_label Optional plain text, up to 32 characters

The result is a list of key, plugin, label and any valid optional fields; unknown fields are removed. Core drops entries from disabled plugins and core-registered providers, and every entry from a plugin whose provider threw or was circuit-broken. A malformed entry is dropped on its own and logged once. The first entry for a full key wins.

Failures, slow listeners and circuit breakers

Each callback runs inside a try/catch (Throwable). If it throws, the service logs an error and continues to later callbacks. For filters, the previously successful value remains. Actions receive no result from the failed callback. An exception inside a listener therefore does not normally abort the caller. Do required validation in the owning service, not in a listener whose exception will be swallowed.

Vetoes fail closed: use veto(), never filter(), for a gate. With filter(), a "deny" listener that throws leaves an earlier listener's "allow" standing, so an access, purchase or equip check fails open. Hook::veto('my.gate', $default, $refusal) returns $refusal the moment any listener throws or is skipped by its circuit breaker. Core's websocket.authorize_channel uses it. A plugin that must also run on engines older than 13 Nov 2026 can check method_exists(app('hook'), 'veto') and fall back to treating a failed listener as a refusal itself.

Transaction-ending database errors propagate. When a listener hits a deadlock, a serialization failure or a lost connection while any connection is inside a transaction, the service logs it and rethrows it, whichever of filter, veto, action or collect was used. The database has already ended the transaction, and carrying on would run the caller's remaining statements outside it. Such an error does not count toward the listener's circuit breaker, because a retried deadlock is the transaction's failure. Other statement errors (a duplicate key, a missing table) fail only that statement and stay isolated, in a transaction or not.

The callback identity is its closure's object hash. Three consecutive failures trip that callback's circuit. Further calls skip it for 300 seconds, with a retry permitted after the cooldown. A successful call resets its failure count. A listener taking more than 500 ms emits a warning after completing. This is a measurement, not an enforced timeout; a blocking callback still blocks PHP.

Circuit and execution state live in memory on the service instance. They are not shared durable state across separate requests or worker processes. Long running workers can retain them longer than ordinary request containers.

Complete inspection and cleanup API

Signature Result
has(string $hookName): bool Whether callbacks are registered
count(string $hookName): int Number of registered callbacks
getHookNames(): array Names currently registered on this instance
getDebugInfo(): array Per-name callback/execution counts and priorities; production returns a message
getCircuitStatus(): array Per-callback failures, trip time, last error and hook name
resetCircuit(?string $callbackId = null): void Reset one callback's circuit or all circuit state
removeCallbacks(string $hookName): void Remove callbacks and the dirty-sort flag
clear(string $hookName): void Remove callbacks for one name
clearAll(): void Remove callbacks, execution counts and circuit state

There is no public method for removing just one closure from a name. Clearing a shared name removes other plugins' listeners too. Reserve it for isolated tests or code that owns that name completely. clear does not reset execution or circuit history; clearAll does.

HookRegistry: definitions rather than execution

HookRegistry stores static definition metadata, independently of HookService. Both AppServiceProvider and HookServiceProvider define core entries during boot. A later define of the same name replaces its earlier metadata.

Signature Result
define(string $hook, array $schema = [], string $version = '1.0', string $stability = 'stable'): void Store/replace a definition
get(string $hook): ?array schema, version, stability, or null
isDefined(string $hook): bool Whether metadata exists
validatePayload(string $hook, mixed $payload): array Error strings; empty for valid, unknown, or empty schema
all(): array Definitions keyed by name
defineCoreHooks(): void Register generic core metadata

Validation is opt-in; HookService::run does not call it. Nonempty schemas expect array fields, not positional arguments. The validator uses PHP gettype names (integer, boolean, string, array, float) and normalizes double to float. Avoid assuming int and bool aliases are normalized. The current object-type branch has limited checking, so do not treat this helper as a security validator. Deprecated entries log warnings when validated.

Verify your integration

Use backend/tests/Unit/HookServiceTest.php for isolated service behavior and backend/tests/Feature/PluginKernelTest.php for engine integration patterns. Test priority order, the actual payload shape, a listener exception, and the caller's resulting behavior. A callback-count assertion alone does not prove that a real request dispatches the hook.

For a missing listener, check the plugin's enabled registry row, discovery path, hooks loader, exact name and dispatcher before clearing caches. For a skipped listener, inspect logs and getCircuitStatus(). For a wrong filter result, check priorities and every non-null return.

Sources: HookService (backend/app/Core/Services/HookService.php), HookRegistry (backend/app/Core/Services/HookRegistry.php), providers (backend/app/Core/Providers), core dispatch callers (backend/app/Core).