WebSocketHandler
in package
Base class for WebSocket connection handlers; extend to define per-connection behaviour.
One WebSocketHandler instance is created per WebSocket connection. The
framework resolves it through the PSR-11 container so constructor parameters
participate in dependency injection. Two special injection attributes are
available:
-
#[FromContext]— injects the live WebSocketContext for the current connection, giving access tosend(),close(), and connection metadata. -
#[FromActor('name')]— injects anActorRefto a named actor registered with the parent WsApplication.
Override the three lifecycle methods to react to connection events.
onMessage() is the only abstract method; onOpen() and onClose() are
optional no-ops by default.
Example — echo handler:
final class EchoHandler extends WebSocketHandler
{
public function __construct(
#[FromContext] private readonly WebSocketContext $ctx,
) }
public function onMessage(WebSocketFrame $frame): void
{
$this->ctx->send($frame->data);
}
public function onClose(int $code): void
{
// cleanup on disconnect
}
}
// Register the handler:
$app->ws('/chat', EchoHandler::class);
Tags
Table of Contents
Methods
- onClose() : void
- Invoked when the WebSocket connection is closed, either by the client or the server.
- onMessage() : void
- Invoked for every WebSocket frame received on this connection.
- onOpen() : void
- Invoked once when the WebSocket handshake completes and the connection is open.
Methods
onClose()
Invoked when the WebSocket connection is closed, either by the client or the server.
public
onClose(int $code) : void
Parameters
- $code : int
-
WebSocket close code (e.g. 1000 for normal closure).
onMessage()
Invoked for every WebSocket frame received on this connection.
public
abstract onMessage(WebSocketFrame $frame) : void
Parameters
- $frame : WebSocketFrame
-
The incoming frame, including opcode and payload.
onOpen()
Invoked once when the WebSocket handshake completes and the connection is open.
public
onOpen() : void
Default implementation is a no-op; override to perform connection setup.