Module notifications
How a module declares notification templates, sends them to players, and what the owner can change in them.
By the end your module sends a player a notification to the bell, by email or to Telegram, and the owner can rewrite its text and turn channels off in the admin. The template holds the text and channels; module code passes only the template key and the variable values.
Minimal example
The Example module tells a report's author that it was closed. A provider declares the template:
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Support;
use Flute\Core\Modules\Notifications\Contracts\NotificationTemplateProviderInterface;
final class Notices implements NotificationTemplateProviderInterface
{
public const REPORT_CLOSED = 'example.report_closed';
public function getModuleName(): string
{
return 'example';
}
public function getNotificationTemplates(): array
{
return [[
'key' => self::REPORT_CLOSED,
'title' => 'example.notify.closed.title',
'content' => 'example.notify.closed.content',
'icon' => 'sl.linear.flag',
'channels' => ['inapp', 'email'],
'variables' => [
'subject' => 'example.notify.vars.subject',
'url' => 'example.notify.vars.url',
],
'components' => [[
'type' => 'actions',
'buttons' => [['label' => 'example.notify.open', 'type' => 'primary', 'url' => '{url}']],
]],
]];
}
}<?php
return [
'notify' => [
'closed' => [
'title' => 'Report closed',
'content' => 'A moderator has reviewed your report "{subject}".',
],
'open' => 'Open',
'vars' => [
'subject' => 'Report subject',
'url' => 'Link to the report',
],
],
];The module's provider registers it in boot():
public function boot(Container $container): void
{
$this->bootstrapModule();
$this->registerNotificationTemplates(new Notices());
}Sending from a service once the report is closed:
notify(Notices::REPORT_CLOSED, $report->author, [
'subject' => $report->subject,
'url' => url('/example/reports/' . $report->id)->get(),
]);How it works
registerNotificationTemplates() only remembers the provider. Templates reach the database on the first send: notify() misses the key, asks every provider and writes their templates. Until then the owner does not see the module's template in the list.
Title, text and button labels can be translation keys. The core translates them into the recipient's language at send time, so new text from a translation file arrives without a re-sync. Variables in a template go in curly braces, {subject}, and are replaced with values from the third argument of notify(). A variable with no value stays in the text as is.
The bell notification's text is parsed as Markdown, and variable values are escaped. A link built from a variable stays a link only if it is an http(s) address or an address on the site; otherwise it becomes #.
Before sending, the core checks three things. If the owner turned the template off, notify() returns false and sends nothing. A channel the template does not list is skipped. A channel the player turned off for this template in their own settings is skipped too. A failure in one channel is logged and does not stop the others.
What the owner sees
The template shows up in AdminNotificationsTemplates. The "Sent by" column shows the module's name, which the core finds by matching getModuleName() against the module key, ignoring case. The owner can change the text, icon, buttons and channels, or turn the template off; see site notifications.
A template the owner edited is marked as customized. A module update does not overwrite it and keeps the original values so the owner can reset the edit. A template with the email channel also appears on the "Emails" tab, where the owner lays out the email. Besides your variables, an email gets {name}, {site_name} and {site_url}.
If a notification is optional, give the owner a switch in the module settings and check it before notify(). The Giveaways module does this: each of its notifications has its own switch.
Many recipients
notify() sends to one user and runs synchronously. Sending to hundreds of players inside a web request drags the response out, and the core has no "template to everyone" method. The module writes a job to the outbox, and the core.outbox background task runs it outside the request:
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Jobs;
use Cycle\Database\Injection\Parameter;
use Flute\Core\Database\Entities\User;
use Flute\Core\Queue\Contracts\JobInterface;
use Flute\Core\Queue\OutboxService;
use Throwable;
final class NotifyJob implements JobInterface
{
public static function write(string $template, array $userIds, array $data): void
{
foreach (array_chunk(array_values(array_unique($userIds)), 200) as $batch) {
app(OutboxService::class)->append('example.notify', [
'queue_job' => self::class,
'data' => ['template' => $template, 'users' => $batch, 'data' => $data],
]);
}
}
public function handle(array $payload): void
{
$ids = array_map(intval(...), (array) ($payload['users'] ?? []));
foreach (User::query()->where('id', 'IN', new Parameter($ids))->fetchAll() as $user) {
try {
notify((string) $payload['template'], $user, (array) $payload['data']);
} catch (Throwable $e) {
// A retry would notify the whole batch again.
logs()->warning('Example: notice not sent', ['user' => $user->id, 'error' => $e->getMessage()]);
}
}
}
}Each job sends one batch of 200 players. This is how the Giveaways module tells participants that a giveaway has been drawn.
For plain text to many users' bells without a template there is notification()->createTextNotificationsForUserIds(). Above 100 recipients it queues the work itself.
Reference
Template fields in getNotificationTemplates():
| Field | Required | What it does |
|---|---|---|
key | yes | template key. Prefix it with the module: example.report_closed |
title, content | yes | title and text: a translation key or a string, variables as {name} |
variables | yes | name => label translation key. The owner sees the labels in the template editor |
icon | no | icon, for example sl.linear.flag |
channels | no | default channels. An empty list means the bell only |
components | no | buttons: [['type' => 'actions', 'buttons' => [['label', 'type', 'url']]]] |
priority | no | order among the module's templates, lower comes first |
layout | no | notification layout, standard by default |
| Function, class | What it does |
|---|---|
notify(string $templateKey, User $user, array $data = [], ?array $channels = null): bool | send a template. $channels replaces the template's channels; the player's choice still applies |
notification()->createTextNotification(User $user, string $title, string $content, ?string $icon = null, ?string $url = null, ?User $actor = null) | a bell notification without a template |
email()->sendTemplate(string $to, string $key, array $data = [], ?string $locale = null, bool $sync = false) | an email from a template on the "Emails" tab |
email()->send(string $to, string $subject, string $body, bool $sync = false, ?string $text = null) | an email with your own HTML |
NotificationChannels::register(DeliveryChannel $channel) | your own delivery channel: key(), label(), available(User), send(User, $title, $body, $url) |
Core channels: inapp (the bell), email, telegram. A module channel that also implements JoinsTemplatesByDefault adds itself to matching templates until the owner edits them.
Common mistakes
Notification template not found: example.report_closed
This log line means the key is neither in the database nor with any provider. Check that registerNotificationTemplates() is called in the provider's boot() and that the key in notify() matches key in the template. notify() returns false in this case.
A variable was not filled in and the text shows :subject. Notification templates write variables as {subject}. The :subject form works in __(), and nothing replaces it in a template.
The owner does not see the template in the list. The module has not sent a notification yet; templates are written on the first send.
Your channel is rejected with "telegram" is not a key a delivery channel may take.: the key belongs to the core (inapp, email, telegram) or does not match ^[a-z][a-z0-9_]{1,31}$.
The module changed a literal string in title, and players still get the old one. The template is already in the database, and the core re-reads providers only when a send misses a key. Write the text as a translation key, and an edit in the translation file shows up at once.