2: The four hooks

phloWS 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 Return
wsConnect a socket opens true to accept, falsey to reject
wsAuth the client sends its auth token true if the token is valid
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:

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: $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.

我们使用必要的cookie来使该网站正常工作。在您的许可下,我们还使用分析工具来改善网站。