Scopes
A scope decides which tabs share a signal and which tabs a broadcast renders again. Every tab has a TAB scope of its own. Give a signal a shared scope, and state that was private becomes multiplayer.
Scope types
| Scope | Shared with | Use case |
|---|---|---|
Scope::TAB |
Nobody (this tab only) | Personal UI state, form input |
Scope::ROUTE |
Every tab on the same route | Live feeds, shared boards, todo lists |
Scope::SESSION |
Every tab of one browser session | User preferences, auth state |
Scope::GLOBAL |
Every tab, on every route | Site-wide banners, system notifications |
'room:lobby' |
The tabs that joined this custom scope | Chat rooms, collaborative documents, teams |
Wherever a context takes a scope, in scope(), addScope(),
removeScope(), signal() and #[Action(scope: ...)],
Scope::ROUTE becomes this route's scope and Scope::SESSION this session's. A
route scope belongs to the route as registered: on /blog/{slug}, Scope::ROUTE
is Scope::routeScope('/blog/{slug}'), shared by every post. For one scope per post, use a
custom scope such as 'post:' . $slug.
Which tabs a scope reaches
A route scope reaches every tab on its route, and Scope::GLOBAL every tab. A session scope
and a custom scope reach the tabs that joined them, which a context does in three ways:
- a signal declared with the scope joins it,
$c->scope($scope)makes it the context's primary scope,$c->addScope($scope)adds it, and$c->removeScope($scope)leaves it again.
$c->signal(0, 'online', 'room:lobby'); // joins room:lobby
$c->addScope('user:' . $userId); // joins user:42 as wellThe primary scope
// The target of $c->broadcast() and the key of a shared render
$c->scope(Scope::ROUTE);
The primary scope does two things: $c->broadcast() renders the tabs in it, and a view
with shareRender: true shares its render with them. It is no default for anything else.
A signal without a scope stays private, so after scope() set a shared scope,
signal() without one throws and names the fix. An action runs for the tab that posts it.
scope() replaces the primary scope set before and keeps the scopes the context joined with
addScope() or a scoped signal.
Scope and the shared render
Each tab renders its own update on a broadcast, which a view that shows anything client-specific (a username, a TAB signal's id, a personal viewport) needs:
$c->addScope($roomScope);
// Renders per tab: the view embeds this user's name and TAB signal ids.
$c->view('room.html.twig', fn (): array => [...]);
If the view really is identical for every tab, set the shared scope with
$c->scope($roomScope) and pass shareRender: true to view(): the
first context renders, and every context with the same primary scope, route and component gets the
same HTML. See Sharing one render.
Broadcasting
A write to a scoped signal broadcasts its scope by itself. To render the tabs of a scope after a change outside signals, such as a database row or GlobalState, broadcast it:
$app->broadcast(Scope::routeScope('/board')); // every tab on /board
$app->broadcast(Scope::sessionScope($c->getSessionId())); // every tab of this session
$app->broadcast('room:lobby'); // the tabs in a custom scope
$app->broadcast('room:*'); // every room
$app->broadcast(Scope::GLOBAL); // every tab
$c->broadcast(); // this context's primary scope
$app->broadcast() takes a resolved scope: the bare Scope::TAB,
Scope::ROUTE and Scope::SESSION throw, since outside a context there is no route
or session to resolve them against. $c->broadcast() on a context whose primary scope is TAB
renders that tab only; reach the scopes it joined with $app->broadcast().
A broadcast from an action or a timer is rendered once on the worker's next flush, however often it was
called, and it reaches the other workers and, with a broker, the other servers.
$app->flushBroadcasts() renders it at once. Config::withBroadcastThrottle()
renders a busy scope at most once per interval, and the last state always arrives:
$config->withBroadcastThrottle('import:*', 250); // each import renders at most 4 times a secondSee Broadcasting for the timing and for presence.
Open a second tab, then increment both counters. The TAB counter belongs to this tab; everyone on this page shares the ROUTE counter.
Session scopes
A session is one browser's session cookie, which all its tabs send. $c->getSessionId()
returns the session's id, a hash of the cookie, and Scope::sessionScope($id) the scope of its
tabs, which is what Scope::SESSION resolves to in a context. The cookie's value never
reaches the page, the Dev Bar, traces or broker messages. Middleware reads the same id from the
via.session request attribute.
$c->regenerateSession() gives the session a new cookie at a login and keeps its id, so its
scope, its SESSION signals and its tabs stay as they are. See
Logging in.
Counting the tabs in a scope
$app->countClients($scope) counts the tabs with an open stream that a broadcast of the scope
reaches, on every worker. Use it to skip work nobody watches:
$app->setInterval(function () use ($app, $prices): void {
if ($app->countClients(Scope::routeScope('/ticker')) === 0) {
return; // nobody is watching
}
$app->setGlobalState('price', $prices->latest());
$app->broadcast(Scope::routeScope('/ticker'));
}, 1000);
A tab counts from its SSE connect until its stream closes. $app->getLocalContexts($scope)
lists this worker's contexts in a scope, connected or not, and $app->getClients() lists
every connected tab.
Custom scopes
Any other string is a custom scope. Tabs that join the same string share its signals and receive its broadcasts:
$app->page('/chat/{room}', function (Context $c, string $room): void {
$roomScope = 'room:' . $room;
$messages = $c->signal([], 'messages', $roomScope); // joins the room
$draft = $c->signal('', 'draft');
$c->action(function () use ($messages, $draft): void {
$messages->mutate(fn (array $list): array => [...$list, $draft->string()]);
$draft->setValue('');
}, 'send');
// ... view ...
});
A pattern with * reaches every matching scope in a broadcast, so 'room:*'
renders every room. With more than one worker or server, a broadcast crosses to the others only for a
scope of up to 256 bytes made of the characters of a URL path: letters, digits,
_ - . ~ : / @ % ! $ & ' ( ) + , ; =, and the { } of a route parameter.
Any other scope, one with a space for example, stays on its worker, and php-via logs a warning once.
Build custom scopes from keys you control. See the chat room example for a full
implementation.
When a scope's signals go
A worker keeps a scope's signals and actions while one of its contexts uses the scope: a tab or a
component that joined it, a tab whose stream is down and whose context has not expired yet, or a page
that registered an #[Action(scope: ...)] for it. When the last of them is destroyed, the
worker drops them, so per-entity scopes such as room:<id> do not add up. With one
worker, the next tab that declares such a signal starts from its initial value again.
With more than one worker, a scoped signal's value also lives in the table the workers share, and it stays there while a context on any worker uses the scope: a tab that declares the signal on another worker gets that value. When the last of them is destroyed, the rows go too. A worker that crashed lets go of its scopes when its replacement starts, and at the latest a minute later. Size the table for the scoped signals in use at peak, see Deployment. Keep a value that has to outlive its visitors in GlobalState or your database, and seed the signal from it:
$visits = $c->signal($app->globalState('visits', 0), 'visits', Scope::ROUTE);Actions and scopes
$c->action() takes no scope: an action runs for the tab that posts it, whatever scopes the
tab is in. A class page can declare #[Action(scope: ...)] to register one action for a
whole scope, which still runs on the posting tab's own instance. See
Composition.
Next steps
- Signals: declaring a shared signal
- Broadcasting: timing, presence and GlobalState
- Views: sharing one render in a scope
- API: Scope: the constants and helpers