问候stackoverflow的人们,最近几天,我一直在研究websockets和一个名为Ratchet的PHP库(这是用PHP编写websockets服务器应用程序的理想选择)。他们在Ratchet官方文档中建议使用SplObjectStorage(我从未听说过)来管理客户端连接对象。
在大多数服务器应用程序中,您可能需要保留有关每个客户端的一些数据(例如,在我尝试编写一个简单的消息传递服务器的情况下,我需要保留诸如客户端的昵称之类的数据,也许还有其他内容),因此据我所知它可以在打开新连接时(如下所示)将客户端对象和包含客户端数据的数组添加到SplObjectStorage。
public function onOpen(ConnectionInterface $conn) {
//$this->clients is the SplObjectStorage object
$this->clients[$conn] = array('id' => $conn->resourceId, 'nickname' => '');
}
Run Code Online (Sandbox Code Playgroud)
但是,我不确定通过数据数组中的值(例如通过用户昵称)从SplObjectStorage中获取对象的最佳方法是什么,一种方法是这样的:
//$this->clients is my SplObjectStorage object where I keep all incoming connections
foreach($this->clients as $client){
$data = $this->clients->offsetGet($client);
if($data['nickname'] == $NickNameIAmLookingFor){
//Return the $client object or do something nice
}
}
Run Code Online (Sandbox Code Playgroud)
但是我认为这样做有更好的方法,因此任何建议都将不胜感激。
提前致谢。