2: The four hooks
Phlo Realtime calls one of four functions in your app for each socket lifecycle event. You implement only the ones you need.
2.1: The lifecycle
| Hook | Called when | Notes |
|---|---|---|
wsAuth |
at the handshake, before the socket is accepted | validate the token; raise an error to refuse |
wsConnect |
right after the socket is accepted | set-up; broadcast via wsCast |
wsReceive |
the client sends a message | nothing; act via wsCast |
wsClose |
a socket closes | nothing |
2.2: The ws-prefixed arguments
Every hook receives connection context under ws-prefixed names so they never collide with your own payload keys:
$wsHostand$wsPort: the host and daemon port the event came from.$wsToken: the client's auth token.$wsSocket: the unique id of this socket....$data: the message payload (forwsReceive).
function wsConnect($wsHost, $wsToken, $wsSocket){
type_presence::create(socket: $wsSocket, since: time())
return true
}
function wsAuth(...$args) => true
function wsReceive($wsHost, $wsToken, $wsSocket, ...$data){
if (($data['type'] ?? null) === 'ping') wsCast(wsTarget: 'socket:'.$wsSocket, toast: 'pong')
}
function wsClose($wsHost, $wsToken, $wsSocket){
type_presence::delete('socket=?', $wsSocket)
}2.3: State lives in the database
Because handlers are short-lived, anything you want to remember between events (who is online, the last message id) goes in a model, exactly like the rest of your app. The demo keeps a presence table and a wslog table and reads them on every event.