looking up data in splobjectstorage
Asked Answered
I

1

7

Greetings people of stackoverflow, for the last days I have been looking at websockets and a PHP library called Ratchet (which is ideal for writing websockets server applications in PHP). In the Ratchet official docs they recommend using SplObjectStorage (which I had never heard of) for managing client connections objects.

In most server applications you probably need to keep some data about each client (e.g. in my case where I'm experimenting with writing a simple messaging server, I need to keep data like the client's nickname and perhaps something more), so as I understand it, I can add the client object and an array with the clients data to the SplObjectStorage when a new connection is opened like here below.

public function onOpen(ConnectionInterface $conn) {
    //$this->clients is the SplObjectStorage object
    $this->clients[$conn] = array('id' => $conn->resourceId, 'nickname' => '');

}

However, I'm not sure what is the best way to get an object from the SplObjectStorage by a value in the data array (like by a users nickname), one way to do it would be like this:

//$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
    }
}

But I sense there is a better way of doing this, so any advices would be greatly appreciated.

Thanks in advance.

Irena answered 1/11, 2013 at 17:16 Comment(1)
I also have this question. And not interested in answers like "no need to do it that way" etc.Nucleotide
R
-2

There is no need to use SplObjectStorage. Make clients an array keyed on resourceId, and do the same for nicknames.

// in __construct()
$this->clients = [];
$this->nicknames = [];

// in onOpen
$this->clients[$conn->resourceId] = $conn;
$this->nicknames[$conn->resourceId] = '';

Then you can access them like so

$this->clients[$conn->resourceId]
$this->nicknamees[$conn->resourceId]

You can have more complicated arrays (maybe you want to put them all in a single nested array), but the solution lies in making the first-level key of that array the resourceId.

Reincarnation answered 1/11, 2013 at 22:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.