Search by

Server-Sent Events for PHP 8.4 (WHATWG HTML §9.2): immutable events, a wire-format serializer that cannot be split by a field value, Last-Event-ID replay, and a request normalizer for kariricode/router.

v4.0.0 2026-11-27 15:27 UTC

This package is auto-updated.

Last update: 2026-12-02 22:57:34 UTC


README

PHP License ARFA Spec

Server-Sent Events for PHP 8.4, following WHATWG HTML §9.2: immutable events, a serializer whose output no field value can split, an emitter for one client connection, a store for Last-Event-ID replay, and a request normalizer that lets kariricode/router route event-stream subscriptions. There is no event loop: you write the loop, in whatever concurrency model your server already has.

Installation

composer require kariricode/sse

Requires PHP 8.4, kariricode/exception ^2.0.2, kariricode/router ^4.1 and psr/http-message ^2.0 (the last two are used only by SseNormalizer).

Quick start

use KaririCode\Sse\Emitter\SseEmitter;
use KaririCode\Sse\Event\SseEvent;

set_time_limit(0);
ignore_user_abort(true); // lets connection_aborted() see the client leave

$emitter = new SseEmitter(retryMilliseconds: 5000);
$emitter->start(); // headers, output buffers off, "retry: 5000"

while ($emitter->isConnected()) {
    $emitter->emit(
        SseEvent::named('sensor.update', json_encode($sensors->read(), JSON_THROW_ON_ERROR))
            ->withId((string) $sequence++),
    );
    sleep(1);
}

$emitter->close();

ping() writes a comment (: ping) that keeps idle proxies from closing the connection. A failed write means the client left: the emitter closes itself and throws StreamException ([SSE_1621]).

Servers that own the connection (ReactPHP, Swoole, RoadRunner) and tests pass a stream instead; the emitter then sends no headers and leaves the stream open on close():

$emitter = new SseEmitter(output: $stream);

Events and the wire format

Field Rule
data any text; each line becomes its own data: line
event no line break; null means the client dispatches message
id no line break or NUL; '' resets the client's last event id
retry zero or more milliseconds

A client ends a line at CR LF, LF and CR, so the serializer splits data at all three: a value cannot smuggle a field such as event: into the frame. An id or event type with a line break is refused when the event is built (InvalidEventException, 1600–1602), and the message never repeats the value.

(new EventSerializer())->serialize(new SseEvent("a\r\nb", 'update', '42', 1000));
// "id: 42\nevent: update\nretry: 1000\ndata: a\ndata: b\n\n"

Replay after reconnection

use KaririCode\Sse\Store\InMemoryEventStore;

$store = new InMemoryEventStore(capacity: 1000);

// when emitting
$event = SseEvent::message($payload)->withId((string) $sequence);
$store->append($event);
$emitter->emit($event);

// when a client reconnects
$lastEventId = $request->getHeaderLine('Last-Event-ID');
if ($lastEventId !== '') {
    $missed = $store->since($lastEventId);   // null: too far behind or unknown
    foreach ($missed ?? [SseEvent::named('snapshot', $state->json())] as $event) {
        $emitter->emit($event);
    }
}

since() returns the events after the id, oldest first; [] when the client is up to date; null when the store no longer holds the id, so you send the full state. InMemoryEventStore serves one process; several processes need a shared store (Redis, a database) behind the EventStore contract.

Router integration

use KaririCode\Router\Core\RouteRegistry;
use KaririCode\Sse\Integration\SseNormalizer;

$routes = new RouteRegistry();
$routes->route([SseNormalizer::METHOD], '/events/{topic}', $subscribe);

$normalizer = new SseNormalizer();
if ($normalizer->canNormalize($request)) {           // Accept: text/event-stream
    $normalized = $normalizer->normalize($request);  // method "SSE", the path
    $result = $routes->match($normalized->method, $normalized->uri);
}

The normalizer claims a PSR-7 server request whose Accept header lists text/event-stream with a quality above zero. */* and text/* do not count, so ordinary page requests stay with the HTTP normalizer.

Errors

Code Exception (family) When
1600–1602 InvalidEventException (Validation) id, event type or retry would break the stream
1610–1612 InvalidConfigurationException (Configuration) negative emitter delay, store capacity below 1, output not a stream
1620 StreamException (Runtime) output started before start()
1621 StreamException (Runtime) a write failed: the client left
1622 StreamException (Runtime) write after close()
1630 UnsupportedRequestException (Validation) normalize() on a request it does not claim

Codes come from block 1600–1699 of the ecosystem registry; messages start with [SSE_<code>].

Development

The toolchain comes from KaririCode Devkit (ADR-004): devkit.php pins PHPUnit, PHPStan, Psalm, PHP-CS-Fixer and Infection, kcode installs them into .kcode/, and they run the configs committed here. Install kcode once, then:

composer install
kcode init          # installs the pinned tools into .kcode/
composer check      # style, PHPStan max, Psalm 1, complexity, tests, mutation
composer security   # composer audit of runtime and toolchain, secret scan
composer sbom       # CycloneDX 1.5 SBOM

Documentation

Document
SPEC-001 architecture, wire format, error model
ADR-001 an emitter without an event loop
ADR-002 no field value can split an event
ADR-003 exception families and block 1600–1699
ADR-004 quality gates through kcode
ADR-005 replay tells "nothing missed" from "too far behind"
QD-V433 measured gates
SECURITY reporting and threat model

License

MIT. See LICENSE.