Search data in splobjectstorage

Greetings to the people of stackoverflow, in recent days I have been looking at websites and a PHP library called Ratchet (which is perfect for writing server applications on web servers in PHP). In Ratchet's official docs, they recommend using SplObjectStorage (which I never heard of) to manage client connection objects.

In most server applications, you probably need to store some data about each client (for example, in my case, when I experiment with writing a simple messaging server, I need to store the data as a click alias and possibly something more), so how I understand, I can add a client object and an array with client data to SplObjectStorage when a new connection is opened, as shown 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 if the best way to get an object from SplObjectStorage is by value in the data array (for example, by the alias of users), one way to do this would be as follows:

//$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 believe that there is a better way to do this, so any advice would be greatly appreciated.

Thanks in advance.

+4
source share
1 answer

No need to use SplObjectStorage. Make an clientsarray with the key resourceIdand 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 this

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

You may have more complex arrays (perhaps you want to put them all in one nested array), but the solution is to make the first level key of this array resourceId.

-2
source

All Articles