Skip to content

Core\Sse\Message::topic

$message->topic(): string

Returns the name of the topic a message was published to.

A stream's script can subscribe to more than one topic with Core\Topic::subscribe. Every value that arrives through Core\Sse->receive is a Core\Sse\Message, and topic() tells you which of those topics it came from. It is a string and never null, because every message on an event stream comes from a topic.

The name is the one the script subscribed to, so the program already knows every name it can see. A value published to a topic the script did not subscribe to never arrives.

The examples below print the topic of each message, use the topic as the event name, and separate messages for one user from messages for everybody.

Return value

Returns string. The topic's name. It is never null, because every message on an event stream comes from a topic. Your program chose the name, not a client, so it is not tainted.

Examples

Where a message came from

<?nvs
// Shows how to read the name of the topic a message was published to.
// The `.nvse` file beside this example publishes two values on `orders`.
Core\Sse $sse = Core\Sse::current();
Core\Topic::subscribe('orders');
?Core\Sse\Message $message = $sse->receive();
while ($message != null) {
// `topic()` returns the topic's name. This prints `orders` two times.
echo $message->topic(), "\n";
$message = $sse->receive();
}
Output
orders
orders

The topic as the event name

<?nvs
// Shows one stream that listens to two topics and uses each topic as the event name.
// The `.nvse` file beside this example publishes on `prices` and on `news`.
Core\Sse $sse = Core\Sse::current();
Core\Topic::subscribe('prices');
Core\Topic::subscribe('news');
?Core\Sse\Message $message = $sse->receive();
while ($message != null) {
// The browser can add one listener for `prices` and another one for `news`.
$sse->send($message->value() as string, event: $message->topic());
$message = $sse->receive();
}
Output
event: prices
data: ACME 18.42
event: news
data: The market opens at nine

A message for one user or for all

<?nvs
// Shows a notification stream for one user of a web app. It gets messages for this
// user and messages for everybody, and marks the second kind.
string $user = 'user:42';
Core\Sse $sse = Core\Sse::current();
Core\Topic::subscribe($user);
Core\Topic::subscribe('everybody');
// The `.nvse` file also publishes a message on `user:7`. It does not arrive here,
// because this stream did not subscribe to that topic.
?Core\Sse\Message $message = $sse->receive();
while ($message != null) {
if ($message->topic() == 'everybody') {
$sse->send($message->value() as string, event: 'announcement');
} else {
$sse->send($message->value() as string, event: 'notification');
}
$message = $sse->receive();
}
Output
event: notification
data: Your invoice is ready
event: announcement
data: The site is down for maintenance at 22:00