Периодическая отправка сообщений клиентам в Ratchet

Я пытаюсь периодически отправлять "Привет, мир!" сообщение всем клиентам, подключенным к чат-серверу, из учебника Ratchet

Я выложу весь код здесь: Chat.php:

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    public $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
            }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    //this worked but I don't want this behaviour
    public function onMessage(ConnectionInterface $from, $msg) {
        /*$numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        foreach ($this->clients as $client) {
            if ($from !== $client) {
                // The sender is not the receiver, send to each client connected
                $client->send($msg);
            }
        }*/
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}

чат-server.php:

<?php
use Ratchet\Server\IoServer;
use MyApp\Chat;

    require dirname(__DIR__) . '/vendor/autoload.php';

    $server = IoServer::factory(
        new Chat(),
        8080
    );

    $server->run();

Чтобы проверить, сколько документов я понял, я добавил таймер в цикл сервера

    <?php
    use Ratchet\Server\IoServer;
    use MyApp\Chat;

        require dirname(__DIR__) . '/vendor/autoload.php';

        $server = IoServer::factory(
            new Chat(),
            8080
        );


        // My code here
        $server->loop->addPeriodicTimer(5, function () {
          echo  "custom loop timer working !";        
        });


        $server->run();

и он работал нормально, выводя эту строку каждые пять секунд после запуска сервера.

Теперь я попытался сделать это так, пытаясь отправить сообщение клиентам, хранящимся в MessageComponentInterface, под названием Chat из учебника.

$server->loop->addPeriodicTimer(5, function () {        
    foreach ($server->app->clients as $client) {                  
            $client->send("hello client");          
    }
});

Но я получаю, что $ server-> app имеет значение NULL, что, вероятно, связано с тем, что я сейчас нахожусь в блоке function (). Я не эксперт по объектно-ориентированному PHP, и этот небольшой проект наверняка поможет мне много. Как я могу получить доступ кMessageComponentInterface называетсяapp свойство сервера внутри таймера, а затем отправлять данные клиентам, хранящимся там?

Ответы на вопрос(1)

Ваш ответ на вопрос