Skip to Content
Module developmentModule basics

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.

app/Modules/Example/Providers/ExampleProvider.php
<?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),
        );
    }
}
app/Modules/Example/Events/PayoutSent.php
<?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,
    ) {
    }
}
app/Modules/Example/Services/Payouts.php
<?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.

NAMEClassWhenWhat it carries
view.before_renderBeforeRenderEventbefore a view rendersgetView(), setView(string) (render another view instead), getData(), setData($key, $value)
view.after_renderAfterRenderEventafter a view rendersgetView(), setView(View)
routing.startedRoutingStartedEventwhen the router is created, before modules loadgetRouteDispatcher()
routing.foundOnRouteFoundEventa route matched, middleware has not run yetgetRoute(), getRequest(), setErrorCode(), setErrorMessage(); after stopPropagation() the answer is an error, 404 by default
routing.finishedRoutingFinishedEventthe route's response is ready, an error includedgetResponse(), setResponse()
flute.responseResponseEventbefore the response is sentgetResponse(), setResponse(); the ETag is set by a listener at priority -100
flute.user.changedUserChangedEventthe balance, profile or avatar frame changedgetUser()
flute.user.sign_ins_revokedSignInsRevokedEventthe core ended all of a player's sign-ins$user
flute.user.block_changedUserBlockChangedEventa block was set or lifted; a block running out is not announced$user, $blocked
flute.user.roles_changedUserRolesChangedEventthe role set changed and is stored$user, $added, $removed (role ids), $cause: admin, grant, expired
flute.user.two_factor_changedUserTwoFactorChangedEventa player turned 2FA on or off$user, $enabled
flute.user.deletingUserDeletingEventan account is about to be deleted from the admin panel$user; an exception in a listener cancels the deletion
flute.settings.savedSettingsSavedEventsettings were written by the admin panel, a command or the API, one event per settings file$section, $keys, changed($key)
flute.grant.expiringGrantExpiringEventthe core.grants task: a temporary role or item runs out within 3 days$user, $grant, $label, $expiresAt
flute.grant.expiredGrantExpiredEventthe core.grants task removed a lapsed role or itemthe same; $grant is already deleted
flute.cosmetic.purchasedCosmeticPurchasedEventa 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.

app/Modules/Example/Services/GameTokens.php
<?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 seeCause
the listener never firesit is in protected array $listen, which a module provider never reads
the listener never firesdispatch() was called without the second argument ::NAME
Non-static method ... cannot be called staticallythe 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 loga listener threw, and the listeners after it did not run
a listener from bootRequest() is not heard in cronthe console never calls bootRequest(); subscribe in boot()
a subscription to an event that already passedregistering after dispatch() does nothing and says nothing

Learn more

On this page