Skip to Content
Basics

Extension points

Where modules and themes plug into the Flute core: events, registries, contracts, container bindings, and how to register from a provider.

By the end of this page you will know which core point to use for what your module needs: subscribing to an event, adding an entry to a registry or implementing a contract. At the end there is a working provider that does all of it from boot(). How a module itself is built is covered in Modules.

The core knows nothing about modules

Dependencies go one way: modules and themes depend on the core, the core does not depend on them. app/Core has no use Flute\Modules\…, no module name, no path to a module and no key of its config, and the core never branches on a module or theme name. The core offers an extension point (a seam) instead, and the module registers itself there.

Before a core commit this command must find nothing but docblock prose, no use statements and no class-name strings:

grep -rn "Flute\\\\Modules\\\\" app/Core

If no point fits and you feel like writing if ($module === 'Shop') in the core, an extension point is missing. It goes into the core, while the feature for one module stays in that module.

Where to register

Everything is wired from the module provider, a subclass of Flute\Core\Support\ModuleServiceProvider. A module provider has no contexts(): it loads in every context, on the site, in the admin panel, in the API and in the console.

MethodWhat goes here
register(Container $container)container bindings: $container->set(Foo::class, \DI\autowire())
boot(Container $container)event subscriptions and registry entries. Runs once per process
bootRequest(Container $container)anything that depends on the current request or user. Needs the RequestBootableInterface interface

In worker mode one process serves many requests, so a decision boot() makes from user() or request() reaches every later visitor. Move such code to bootRequest().

Core extension points

SeamEntry pointWhen to use it
Container bindings and boot orderFlute\Core\Support\ModuleServiceProvider (register(), boot()), class listed in module.json.providersalways: this is the module's entry (Module provider)
Events and listenersapp/Core/Events/* through events() (FluteEventDispatcher); core providers are wired by Flute\Core\EventListenerRegistrarreact to something the core did, or change a template or response on the fly (Events and listeners)
Contractsapp/Core/Contracts/*, see belowthe core calls your class at a known place
Permissionsmodule.json.permissions[] → Flute\Core\Authorization\PermissionRegistry, per-record permissions in PolicyRegistryyour own permissions in roles, user()->can('x', $record) checks (Module permissions)
Routes and API#[Route] on a module controller, Api\ApiRegistry, Api\Scope\ScopeRegistryyour own pages and /api/v1 resources (Module routes, middleware and API)
Page blocks and zonesModules\Sections\Sections\ModuleBlocks::register($key, $class), ModuleZones::register($owner, $labelKey) over SectionRegistry and ZoneRegistrya block the owner places in Studio; zones above and below the module's page (Blocks and zones for Studio)
Admin panelAdmin\UI\Settings\SettingsRegistry, Admin\UI\Action\ActionRegistry, Admin\UI\Surface\AdminSurfaceRegistry, Admin\UI\Home\HomeProviderRegistry, Admin\UI\Home\Setup\SetupChecklist, Admin\UI\Onboarding\AnnouncementRegistrymodule settings, actions, admin home widgets, setup checklist steps, announcements (Module admin, Module settings, Admin embedding)
Cards and profilesSurfaces\SurfaceRegistry with keys from Surfaces\SurfaceKeysa player tab, a line in the user card, a menu item, an avatar (Admin embedding)
Interactive componentsWire\WireRegistry (lazy($id, $class))a component re-rendered by the server (Live filters and forms)
SitemapSitemap\SitemapProviderRegistrymodule addresses in /sitemap.xml (Module sitemap, search and metrics)
Metricsa class with the #[MetricsContributor] attribute in the Surfaces/ folder, method collect(MetricSink $sink). Metrics\MetricRegistry lives for one request, so a counter bumped on an ordinary page never reaches /metricsmodule figures in /metrics (Module sitemap, search and metrics)
Global searchModules\GlobalSearch\Services\SearchRegistrymodule results in search (Module sitemap, search and metrics)
AssistantAi\Tools\ToolRegistry, Ai\Capabilities\CapabilityRegistry (by class name from boot())tools and capabilities for the assistant module
Server panelsAdmin\Packages\Server\Services\PanelProviderRegistryyour own control panel for game servers
StudioModules\Studio\Decor\DecorRegistry, Modules\Studio\Fonts\FontRegistry, Modules\Studio\Presets\PresetRegistrydecor, fonts and palettes. These registries read theme folders and have no register() (Theme parameters, What modules and themes add to Studio)
Theme resolutionFlute\Core\Theme\ThemeManager (getCurrentTheme(), setTheme(), loadThemeJson())get the current theme instead of naming one in code (How themes work)
Module lifecycleFlute\Core\ModulesManager\{ModuleManager, ModuleFinder, ModuleDependencies}check that another module is installed and active (Module provider)

Classes without a prefix live under Flute\Core\; Admin\ means Flute\Admin\ (folder app/Core/Modules/Admin/). The most detailed catalogue, with when each point fires, is the "Extension points" section of app/Core/AGENTS.md.

Events

Subscribe in boot() with events()->addListener(). Pass a closure that pulls the listener from the container: a [Listener::class, 'method'] pair fails on dispatch unless the method is static. The module provider's $listen property is not read.

events()->addListener(
    SignInsRevokedEvent::NAME,
    static fn(SignInsRevokedEvent $e) => app(RevokeGameTokens::class)->handle($e),
);

The third argument is the priority, higher runs earlier. In worker mode a subscription made in bootRequest() is dropped after the request.

EventNAMEWhen it fires
BeforeRenderEventview.before_renderbefore a template renders through view() or template()->render(), not for @include. setView() swaps the template, setData() adds a variable
AfterRenderEventview.after_renderafter rendering; the finished View can be replaced
RoutingStartedEventrouting.startedwhen the router is created, once per process
OnRouteFoundEventrouting.founda route matched and middleware has not run yet. A stopped event returns an error with the code from setErrorCode()
RoutingFinishedEventrouting.finishedthe response is ready, error pages included. The response can be replaced
ResponseEventflute.responseafter the request is handled, before the response is sent. The response can be replaced
UserChangedEventflute.user.changeduser data changed (profile, balance, frame, cosmetics, updateUser()) or the user became the current one: sign-in, registration, an API request with a token
UserRolesChangedEventflute.user.roles_changedthe role set changed and is stored. Carries added, removed (role ids) and cause
UserBlockChangedEventflute.user.block_changeda user was blocked or unblocked. A block that runs out on its own is not announced
UserTwoFactorChangedEventflute.user.two_factor_changeda user turned 2FA on or off
SignInsRevokedEventflute.user.sign_ins_revokedevery sign-in of the user has ended: password change or reset, 2FA turned on or off, ending sessions, a block, a deletion. This is where a module revokes its own tokens and links
UserDeletingEventflute.user.deletingthe account is about to be deleted. An exception in a listener stops the deletion
SettingsSavedEventflute.settings.savedsettings were written by anyone: the admin panel, a command, the API. One event per config file; changed('shop.slug') checks a key
CosmeticPurchasedEventflute.cosmetic.purchaseda cosmetic purchase went through: money debited, ownership stored
GrantExpiringEventflute.grant.expiringa time-limited role or cosmetic expires soon. Sent by the core.grants task once per period
GrantExpiredEventflute.grant.expireda time-limited role or cosmetic has expired and was removed

Role, block and 2FA events arrive after the database write, and a failing listener does not roll the change back. Besides app/Core/Events, events live next to their areas: app/Core/Modules/Auth/Events, Modules/Payments/Events, Players/Events, Theme/Events (theme.activated, theme.installed…), ModulesManager/Events, Moderation/Events, Discussion/Events.

Contracts

InterfaceWhat the module implementsHow to wire it
RequestBootableInterfacebootRequest() on the providerimplements on the provider
SitemapProviderurls(): iterable yielding loc and optionally lastmod, changefreq, prioritySitemapProviderRegistry->register()
UserAvatarProviderInterfaceavatarUrl(User $user): ?string for a user still on the default avatar. Called on every avatar render, so no network or database callsSurfaceRegistry->add(SurfaceKeys::USER_AVATAR, ...)
FluteComponentInterfacea server component with boot(), render(), set(), validate()base class Flute\Core\Support\FluteComponent
ServiceProviderInterfacea core provider with contexts()core only. A module extends ModuleServiceProvider

An interface goes into app/Core/Contracts when the core has its own default implementation and a module may swap in another.

Example: a module provider

The MyFeature module revokes its game tokens when a user loses every sign-in, adds a page to the sitemap and registers a Studio block.

app/Modules/MyFeature/Listeners/RevokeGameTokens.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\MyFeature\Listeners;

use Flute\Core\Events\SignInsRevokedEvent;
use Flute\Modules\MyFeature\Services\GameTokens;

final class RevokeGameTokens
{
    public function __construct(
        private readonly GameTokens $tokens,
    ) {
    }

    public function handle(SignInsRevokedEvent $event): void
    {
        $this->tokens->revokeFor($event->user);
    }
}
app/Modules/MyFeature/Support/LeaderboardPages.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\MyFeature\Support;

use Flute\Core\Contracts\SitemapProvider;

final class LeaderboardPages implements SitemapProvider
{
    public function urls(): iterable
    {
        yield ['loc' => route('frags.index'), 'changefreq' => 'daily', 'priority' => 0.5];
    }
}
app/Modules/MyFeature/Providers/MyFeatureProvider.php
<?php

declare(strict_types = 1);

namespace Flute\Modules\MyFeature\Providers;

use DI\Container;
use Flute\Core\Events\SignInsRevokedEvent;
use Flute\Core\Modules\Sections\Sections\ModuleBlocks;
use Flute\Core\Sitemap\SitemapProviderRegistry;
use Flute\Core\Support\ModuleServiceProvider;
use Flute\Modules\MyFeature\Listeners\RevokeGameTokens;
use Flute\Modules\MyFeature\Studio\LeadersSection;
use Flute\Modules\MyFeature\Support\LeaderboardPages;

final class MyFeatureProvider extends ModuleServiceProvider
{
    public function register(Container $container): void
    {
    }

    public function boot(Container $container): void
    {
        $this->bootstrapModule();

        events()->addListener(
            SignInsRevokedEvent::NAME,
            static fn(SignInsRevokedEvent $e) => app(RevokeGameTokens::class)->handle($e),
        );

        $container->get(SitemapProviderRegistry::class)->register(new LeaderboardPages());

        if (!ModuleBlocks::has(LeadersSection::key())) {
            ModuleBlocks::register(LeadersSection::key(), LeadersSection::class);
        }
    }
}

LeadersSection extends Sections\Sections\Section with a key like myfeature.leaders: owner and name joined by a dot, lowercase Latin letters and digits. The key must match LeadersSection::key(), or register() throws. The core recommends checking ModuleBlocks::has() before registering.

Modules and themes

A theme overrides module templates without registering anything: the file app/Themes/<theme>/views/modules/<namespace>/<same path> wins over the module's template on public pages. For such a copy to call methods of your objects, the module allows them in boot():

ThemeLintMethods::register('percent', 'isClosed');

Only read methods are allowed: register() refuses names that write, query or take a callable on core objects. The class is Flute\Core\Theme\Authoring\ThemeLintMethods.

A module can also replace a core template itself. Files under template()->overrideViews($this->getModulePath('Resources/overrides')) win over every theme, and a BeforeRenderEvent listener with setView() swaps one page by name.

More

On this page