Module sitemap, search and metrics
How a module adds its addresses to sitemap.xml, its results to the site search and the admin search, and its own values to /metrics.
By the end the module's player pages are in /sitemap.xml, players can be found through the site search and the admin search, and /metrics reports the number of ranked players. Each of the four parts is registered on its own, so take only the ones you need.
Sitemap
The core adds static GET routes without parameters to the sitemap by itself, and Studio pages too. A provider is for addresses with parameters: a player page, a news post, a product.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Support;
use Flute\Core\Contracts\SitemapProvider;
use Flute\Modules\Example\Services\Leaderboard;
final class ExampleSitemap implements SitemapProvider
{
public function urls(): iterable
{
foreach (app(Leaderboard::class)->top(500) as $row) {
yield [
'loc' => route('example.player', ['id' => (int) $row['id']]),
'lastmod' => (string) $row['updated'],
'changefreq' => 'daily',
'priority' => 0.6,
];
}
}
}use Flute\Core\Sitemap\SitemapProviderRegistry;
use Flute\Modules\Example\Support\ExampleSitemap;
$container->get(SitemapProviderRegistry::class)->register(new ExampleSitemap());Return addresses with yield instead of an array: the sitemap holds up to 50,000 addresses, and an array that size eats memory. loc may be a path from the root, and the core adds the site address. priority is clamped to 0–1 and written with one decimal, and a missing changefreq or priority comes from config/sitemap.php (weekly and 0.5). The Shop module's catalog and the Clans module's clan pages work this way.
How it works
GET /sitemap.xml is built from routes first, then from providers. Studio pages come from a core provider registered before modules. When an address appears twice, the first entry stays. Routes with auth, can, token, htmx and similar middleware stay out of the sitemap, and so do paths from exclude_prefixes (/admin, /api, /profile, /wire and others). A provider that throws is skipped, and the log gets Sitemap provider failed: <message>.
The finished sitemap is cached for sitemap.cache_ttl seconds, an hour by default. A new address shows up once the cache expires. A module has no way of its own to drop the sitemap earlier; php flute cache:clear empties it.
Site search
The site search asks every enabled provider in SearchRegistry and shows the results in groups, one group per provider.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Support;
use Flute\Core\Modules\GlobalSearch\Contracts\SearchProviderInterface;
use Flute\Core\Modules\GlobalSearch\DTO\SearchQuery;
use Flute\Core\Modules\GlobalSearch\DTO\SearchResult;
use Flute\Modules\Example\Services\Leaderboard;
final class ExampleSearch implements SearchProviderInterface
{
public function getKey(): string
{
return 'example';
}
public function getTitle(): string
{
return (string) __('example.search.title');
}
public function getDescription(): string
{
return (string) __('example.search.description');
}
public function getIcon(): string
{
return 'sl.linear.cup-star';
}
public function isEnabledByDefault(): bool
{
return true;
}
public function search(SearchQuery $query): array
{
return array_map(
fn(array $row): SearchResult => new SearchResult(
provider: $this->getKey(),
providerTitle: $this->getTitle(),
id: (int) $row['id'],
title: (string) $row['name'],
url: route('example.player', ['id' => (int) $row['id']]),
subtitle: (string) __('example.search.score', ['score' => (int) $row['score']]),
image: (string) $row['avatar'],
relevance: mb_strtolower((string) $row['name']) === $query->valueLower ? 3 : 1,
),
app(Leaderboard::class)->search($query->value, 'score', min(20, $query->limit)),
);
}
}use Flute\Core\Modules\GlobalSearch\Services\SearchRegistry;
use Flute\Modules\Example\Support\ExampleSearch;
$container->get(SearchRegistry::class)->register(new ExampleSearch());SearchService drops queries shorter than search.min_length (2 characters), removes duplicates and sorts by relevance, then by title. An exception from search() goes to the modules log as Search provider example failed: <message>, and the other providers answer as usual. A provider that also implements BrowsableSearchProviderInterface with browse(int $limit) returns a list with no query when the visitor picks only its group; the News module's news search does this.
The owner turns providers on and off on the "Search Settings" page (/admin/search-module/settings), which also holds the "Only for authenticated users" switch, on by default. Put into the search only what a guest would see on the site anyway.
Admin search
The admin search (⌘K) runs on the AdminSearchEvent event, not on a registry. A listener gets the string and adds results, and checks permissions itself.
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Admin;
use Flute\Admin\Packages\Search\Events\AdminSearchEvent;
use Flute\Admin\Packages\Search\Services\AdminSearchResult;
use Flute\Admin\Packages\Search\Services\SearchMatch;
use Flute\Modules\Example\Services\Leaderboard;
final class PlayerSearchListener
{
public static function handle(AdminSearchEvent $event): void
{
$term = trim($event->getValue());
if (!$event->wants('example') || mb_strlen($term) < 2 || !user()->can('admin.example')) {
return;
}
foreach (app(Leaderboard::class)->search($term, 'score', 5) as $row) {
$event->add(( new AdminSearchResult(
(string) $row['name'],
(string) url('/admin/example/players/' . (int) $row['id']),
'sl.linear.cup-star',
(string) __('example.admin.search_group'),
SearchMatch::score($term, (string) $row['name']),
) )->setGroup('example'));
}
}
}use Flute\Admin\Packages\Search\Events\AdminSearchEvent;
use Flute\Modules\Example\Admin\PlayerSearchListener;
events()->addListener(AdminSearchEvent::NAME, [PlayerSearchListener::class, 'handle']);Results are grouped by setGroup(), and the group label comes from the fourth argument. The prefixes @, >, / and # narrow the search to core groups, so a module's group shows only in a search without a prefix, 5 rows at most.
relevance is on a 0–100 scale, which is what SearchMatch::score() returns; the core multiplies a value of 10 or less by 9, the scale of older listeners. A listener that throws is skipped, and the log gets Admin search provider failed. The owner's side is in Admin dashboard and search.
Metrics
GET /metrics serves values in the Prometheus format: build, memory, queue, cache. A module adds its own with a class carrying the #[MetricsContributor] attribute in its Surfaces/ folder, which the core scans in bootstrapModule().
<?php
declare(strict_types = 1);
namespace Flute\Modules\Example\Surfaces;
use Flute\Core\Metrics\Contracts\MetricsContributor;
use Flute\Core\Metrics\MetricSink;
use Flute\Core\Surfaces\Attributes\MetricsContributor as Metrics;
use Flute\Modules\Example\Services\Leaderboard;
#[Metrics]
final class ExampleMetrics implements MetricsContributor
{
public function collect(MetricSink $sink): void
{
$sink->gauge('example_ranked_players', (float) app(Leaderboard::class)->count(), help: 'Players in the ranking');
}
}collect() runs on every request to /metrics, so use what is already in memory or takes one light query. An error in it doesn't break the response: that value disappears and the rest stay. Names and labels that break Prometheus rules are fixed by the core, which replaces the extra characters with _. Metrics\MetricRegistry lives for one request and is what collect() receives, so a counter() call from an ordinary page never reaches /metrics. Keep the counter yourself (in the database or cache) and report its current value in collect(). The BrowserPush and Monitoring modules' metrics work this way.
Without metrics.token only an administrator can open the address. With a token, a scraper reads it with an Authorization: Bearer <token> header or a ?token= parameter. With metrics.enabled = false the address answers 404.
Reference
| Method | What it does |
|---|---|
SitemapProviderRegistry::register(SitemapProvider $provider): void | adds a sitemap provider, the same object is not added twice |
SitemapProvider::urls(): iterable | entries {loc, lastmod?, changefreq?, priority?} |
SearchRegistry::register(SearchProviderInterface $provider): void | adds a search provider; the same getKey() replaces the earlier one |
SearchResult(provider, providerTitle, id, title, url, subtitle?, icon?, image?, relevance = 0, meta = []) | one result row, providerTitle goes through __() |
AdminSearchEvent::wants(string $group): bool | whether the group is wanted under the current search prefix |
MetricSink::gauge(string $name, float $value, array $labels = [], string $help = '') | a value; counter() and observe() exist too |
Common mistakes
| Message or symptom | Cause |
|---|---|
a new address is missing from /sitemap.xml | the sitemap is cached for an hour, or the route has auth or can middleware |
Sitemap provider failed: <message> in the log | urls() threw, and the whole provider was skipped |
| a guest doesn't see the search | "Only for authenticated users" is on in the search settings |
| the module's results are missing from the search | the provider is off in the search settings, or another module registered the same key later |
Search provider example failed: <message> in the modules log | search() threw |
| the admin search shows records the admin may not see | the listener didn't check user()->can() |
a value is always 0 in /metrics | it was counted with counter() on an ordinary page instead of in collect() |