provm / events
WebSocket 事件处理器
Requires
- cboden/ratchet: ^0.4.3
- psr/event-dispatcher: ^1.0
Requires (Dev)
- kint-php/kint: ^3.3
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-29 05:56:32 UTC
README
WebSockets PHP 应用。使用 Ratchet 作为基础创建应用,它可以作为连接数据库的 框架 从网页 UI。
简介
我编写这个项目是因为很难找到任何替代方案来处理使用 PHP 的服务器端 WebSocket。 Ratchet 处理连接,但不处理应用本身。我需要一个类似于 Slim 的应用结构,这是我正在使用的。这就是结果。
安装
使用 composer。
composer require aldarien/events
使用
我建议您使用容器如 PHP-DI 设置您的 应用。
基本示例:
$app = ProVM\Common\Alias\Server\App::factory(
new Ratchet\Server\HttpServer(
new Ratchet\Server\WsServer(
new ProVM\Common\Alias\Event\Message(new SplObjectStorage())
)
),
$port ?? 8010
);
$app->add('event_name', function($request, $response) {
// do action
return $response;
})
$app->run();
分解:
应用创建与 Ratchet 类似,使用包装器 ProVM\Common\Alias\Server\App,但消息处理程序来自此包 ProVM\Common\Alias\Event\Message,它处理所有事件分派和监听器。
然后通过 $app->add 添加事件(s),它需要一个事件名称和一个类似于 Slim 控制器的可调用处理程序。
最后只需 $app->run
您可以为可调用项使用 监听器
class Handler {
public function __invoke($request, $response) {
// do something else
return $response;
}
public function other($request, $response) {
// other action
return $response;
}
}
$app->add('event2', new Handler());
$app->add('other', [new Handler(), 'other']);
在网页 UI 中只需创建一个 WebSocket
var conn = new WebSocket(websocket_url)
conn.onopen = function(e) {
// open event
}
conn.onmessage = function(e) {
// listen to messages received
}
conn.onerror = function(e) {
console.error(e)
}
conn.onclose = function(e) {
// check if e.code == 1000 closed without error)
}
msg = {
action: 'event_name',
data: []
}
conn.send(JSON.stringify(msg))
分解:
创建 WebSocket 连接 new WebSocket(websocket_url) 其中 websocket_url 可以是类似 ws://:8010 或 wss://:8010 的东西,端口号与应用中设置的一致。
设置 open、message、error 和 close 的事件监听器,并使用 send 开始发送消息
请注意最后几行,应用程序接收到的消息需要与之前添加的事件名称等价的操作,以及任何关联的数据(可能不存在)。