I have a scenario where an array of objects (Players) must be read and modified by objects of other classes. Those objects will work on the same array, that is, any change to the array is seen by all objects. Anything is likely to modify the array including threads and IO event functions.
Here are the specifics:
class Player {
public $connection;
public $x,$y,$velocity;
public function __construct(ConnectionInterface $conn, $initx, $inity)
{ /* ... */ }
public function updateVelocity($newVelocity) { /* ... */ }
}
$players_arr = array();
class ConnectionClass extends Thread implements MessageComponentInterface {
private $players;
// A new player connected
public function onOpen(ConnectionInterface $conn) {
// ...
array_push($this->players, new Player($conn, x, y);
}
public function run() {
while(true) {
// ...
foreach ($this->players as $player)
$player->connection->send(data);
sleep(1);
}
}
}
class World extends Thread {
private $players;
public function run() {
while(true) {
// ...
foreach ($this->players as $player)
$player->updateVelocity($vel);
usleep(30000);
}
}
}
$players in World and in ConnectionClass should always be identical!!
The ConnectionInterface and MessageComponentInterface are part of "Ratchet" a Web-Socket library I'm using. Also, if it makes any difference, each class is in its own .php file.
How should I structure the code?
Should I make the shared array static in Player class itself? if so, how to access it from other classes?
Things I've tried:
- passing a reference of
$players_arrto the classes' constructors and assigning it to$players: gotcannot assign by reference to overloaded objecterror. http://ift.tt/1UhMNjc - using
ArrayObject: adding anew Player()to it inonOpen()is not yielding no effects. (Could have done wrong?) Sharing array inside object through classes in php
Note: I'm aware that multi-threaded access to the array requires special measures and synchronization (Please elaborate), but the main issue is how to share the array across classes (not necessarily threads)
Aucun commentaire:
Enregistrer un commentaire