Events and listeners
How a module subscribes to core events, declares its own events for other modules, and ends its own player credentials on SignInsRevokedEvent.
By the end your module reacts to core events, such as a player changing their password, and tells other modules about its own events.
Minimal example
The Example module stores game tokens for players. When the core ends a player's sign-ins, Example deletes that player's tokens. The module also announces every payout with the example.payout_sent event.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Providers;
use DI\Container;
use Flute\Core\Events\SignInsRevokedEvent;
use Flute\Core\Support\ModuleServiceProvider;
use Flute\Modules\Example\Services\GameTokens;
final class ExampleProvider extends ModuleServiceProvider
{
public function boot(Container $container): void
{
$this->bootstrapModule();
events()->addListener(
SignInsRevokedEvent::NAME,
static fn(SignInsRevokedEvent $e) => app(GameTokens::class)->revokeAll($e->user),
);
}
}<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Events;
use Flute\Core\Database\Entities\User;
use Symfony\Contracts\EventDispatcher\Event;
final class PayoutSent extends Event
{
public const NAME = 'example.payout_sent';
public function __construct(
public readonly User $user,
public readonly int $amount,
) {
}
}<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Services;
use Flute\Core\Database\Entities\User;
use Flute\Modules\Example\Events\PayoutSent;
use Throwable;
final class Payouts
{
public function pay(User $user, int $amount): void
{
db()->insert('example_payouts')->values(['user_id' => $user->id, 'amount' => $amount])->run();
try {
events()->dispatch(new PayoutSent($user, $amount), PayoutSent::NAME);
} catch (Throwable $e) {
logs('modules')->warning('example: payout event failed: ' . $e->getMessage());
}
}
}The listener is a closure, so the service class loads only when the event arrives. The event goes out after the database write, and a failing listener cannot undo a payout that already happened. The Tickets module declares and sends its events the same way, and the Discord module listens to them.
How it works
events() returns Flute\Core\Support\FluteEventDispatcher, a subclass of the Symfony EventDispatcher. Events are matched by the NAME string, so the second argument of dispatch() is required: without it no subscriber receives the event. There are no event() or dispatch() helpers.
Subscribe in the provider's boot(). It runs in every context, so the listener fires on the site, in cron and in the queue alike. A listener added in bootRequest() never appears in the console, and in worker mode it is removed after the request.
Listeners with a higher priority run first; the default is 0: events()->addListener($name, $listener, 10). An event that extends the Symfony Event can be stopped with $event->stopPropagation(), and later listeners do not receive it. The core itself checks for a stop on routing.found and routing.finished, where an error goes out instead of the page, and on theme.installed, theme.activated and theme.uninstalled, where a stop cancels the theme action.
The dispatcher does not catch listener exceptions. An exception ends the handling of the event, and the listeners after it never get it. Most core events are sent inside a try and the error only reaches the log. view.before_render, flute.response and flute.settings.saved are not wrapped, so an error there breaks the page or the save. Catch errors inside your own listener.
Core events
The classes live in app/Core/Events, namespace Flute\Core\Events.
NAME | Class | When | What it carries |
|---|---|---|---|
view.before_render | BeforeRenderEvent | before a view renders | getView(), setView(string) (render another view instead), getData(), setData($key, $value) |
view.after_render | AfterRenderEvent | after a view renders | getView(), setView(View) |
routing.started | RoutingStartedEvent | when the router is created, before modules load | getRouteDispatcher() |
routing.found | OnRouteFoundEvent | a route matched, middleware has not run yet | getRoute(), getRequest(), setErrorCode(), setErrorMessage(); after stopPropagation() the answer is an error, 404 by default |
routing.finished | RoutingFinishedEvent | the route's response is ready, an error included | getResponse(), setResponse() |
flute.response | ResponseEvent | before the response is sent | getResponse(), setResponse(); the ETag is set by a listener at priority -100 |
flute.user.changed | UserChangedEvent | the balance, profile or avatar frame changed | getUser() |
flute.user.sign_ins_revoked | SignInsRevokedEvent | the core ended all of a player's sign-ins | $user |
flute.user.block_changed | UserBlockChangedEvent | a block was set or lifted; a block running out is not announced | $user, $blocked |
flute.user.roles_changed | UserRolesChangedEvent | the role set changed and is stored | $user, $added, $removed (role ids), $cause: admin, grant, expired |
flute.user.two_factor_changed | UserTwoFactorChangedEvent | a player turned 2FA on or off | $user, $enabled |
flute.user.deleting | UserDeletingEvent | an account is about to be deleted from the admin panel | $user; an exception in a listener cancels the deletion |
flute.settings.saved | SettingsSavedEvent | settings were written by the admin panel, a command or the API, one event per settings file | $section, $keys, changed($key) |
flute.grant.expiring | GrantExpiringEvent | the core.grants task: a temporary role or item runs out within 3 days | $user, $grant, $label, $expiresAt |
flute.grant.expired | GrantExpiredEvent | the core.grants task removed a lapsed role or item | the same; $grant is already deleted |
flute.cosmetic.purchased | CosmeticPurchasedEvent | a cosmetic purchase is stored and paid for | $user, $ownership, $itemName |
routing.started fires before the core calls the modules' boot(), so a module listener never sees it. The News and BrowserPush modules reload their settings on flute.settings.saved, and Whitelist recounts access on flute.user.block_changed and flute.user.roles_changed.
Module credentials when sign-ins end
auth()->revokeSignIns($user) ends everything that acts as the player: sessions with their remembered devices, personal and OAuth tokens, authorization codes and links sent by email. The core calls it on a password change or reset, when 2FA is turned on or off, on "end all sessions", on a block and on account deletion. Once the deletions are committed, flute.user.sign_ins_revoked arrives.
A module removes its own credentials in a listener for this event: a bot link, a game token, a launcher key. Without the listener they outlive a ban or a password change. The event carries only $user. It also arrives when the player ended the other sessions and kept the current one.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Services;
use Flute\Core\Database\Entities\User;
final class GameTokens
{
public function revokeAll(User $user): void
{
db()->delete('example_game_tokens', ['user_id' => $user->id])->run();
}
}When the module blocks a player itself, call UserBlockChangedEvent::announce($user, true) after the commit: it ends the sign-ins and sends the event. revokeSignIns() called inside a transaction throws a LogicException with Sign-ins are revoked after the change commits, not inside a transaction.
Common mistakes
| What you see | Cause |
|---|---|
| the listener never fires | it is in protected array $listen, which a module provider never reads |
| the listener never fires | dispatch() was called without the second argument ::NAME |
Non-static method ... cannot be called statically | the listener is a [Listener::class, 'handle'] pair with a non-static method; pass a closure or a built object [app(Listener::class), 'handle'] |
Sign-ins revoked listener failed: ... in the log | a listener threw, and the listeners after it did not run |
a listener from bootRequest() is not heard in cron | the console never calls bootRequest(); subscribe in boot() |
| a subscription to an event that already passed | registering after dispatch() does nothing and says nothing |
The other events live next to their subsystems. Class namespaces and NAME values:
| Namespace | Events |
|---|---|
Flute\Core\Modules\Auth\Events | flute.user_registered, flute.user_logged_in, flute.user_logged_out, flute.user_verified, flute.social_logged_in, flute.social_provider_added, flute.social_provider_removed, flute.password_reset_requested, user.authenticating, user.registering, auth.login.validating, auth.register.validating, auth.login.form.rendering, auth.register.form.rendering |
Flute\Core\Modules\Payments\Events | payment.before, payment.before_invoice_created, payment.after_created, payment.success, payment.failed, payment.refunded, payment.dispute_opened, payment.dispute_resolved, purchase.completed, purchase.refunded, gateway.before_processing, gateway.after_response, flute.payment.register |
Flute\Core\Players\Events | flute.player.linked, flute.player.unlinked, flute.player.merged, flute.player.unmerged, flute.player.session_started, flute.player.session_ended, flute.player.killed, flute.player.sanction_reported, flute.match.round_ended |
Flute\Core\ModulesManager\Events | module.registered, module.install, module.activate, module.disable, module.update, module.delete |
Flute\Core\Theme\Events | themes.initialized, theme.installed, theme.activated, theme.deactivated, theme.uninstalled, theme.Changed |
Flute\Core\Moderation\Events | flute.moderation.restricted, flute.moderation.restriction_lifted, flute.moderation.reported, flute.moderation.report_resolved, flute.moderation.item_announced, staff_kpi.period.closed |
Flute\Core\Discussion\Events | flute.discussion.comment_posted, flute.discussion.comment_published, flute.discussion.comment_removed, flute.discussion.reaction_changed |
| other | flute.webhook.fired (Webhooks\Events\WebhookEventFired), flute.server.delivery_finished (Servers\Events\CommandDeliveryFinished), flute.gamelink.event (Api\GameLink\Events\GameLinkEventReceived), flute.lang_changed (Modules\Translation\Events\LangChangedEvent), template.initialized (Template\Events\TemplateInitialized) |
Flute\Core\EventListenerRegistrar wires listeners from an "event → classes" map. On every event it takes the class from the container and calls its handle(). It sends an error to ExceptionReporter and swallows it outside debug mode, so the following listeners still run. This is how the core wires the protected array $listen of its own providers. A module can call it from boot():
$container->get(EventListenerRegistrar::class)->register([
SignInsRevokedEvent::NAME => [RevokeGameTokens::class],
]);events()->addDeferredListener($name, $listener, $priority) stores the listener in the cache and attaches it when the dispatcher is created, before modules load. The core only passes a class and static method pair there, for example [BalanceSignal::class, 'onResponse'].
To let the owner receive a module event by webhook, register it in boot(): WebhookEvents::register(PayoutSent::NAME, 'example.webhooks.payout_sent', 'admin.example'), and when sending also call app(WebhookService::class)->dispatch(PayoutSent::NAME, $payload). The event name uses Latin letters, digits and _, with at least two parts joined by a dot. The Tickets module does this. How the owner sets up webhooks is in Webhooks.