title: How to handle sockets in PHP
body: <p>I am using <a href="http://socketo.me/" rel="nofollow noreferrer">Ratchett</a> to create sockets on my web server with PHP.</p>
  
  <p>Currently I have <strong>A</strong> - the server, <strong>B</strong> - a device looking for a change on a database(in <strong>A</strong>) and  <strong>C</strong> - a device making the change on the database(in <strong>A</strong>) with a <code>curl</code> request.</p>
  
  <p>Currently when <strong>C</strong> makes the change I store the change in the database on <strong>A</strong>. Mean while <strong>B</strong> is checking every second with <strong>A</strong> through a socket whether there is an item is in the database by sending a request to <strong>A</strong> in which <strong>A</strong> returns a response. This is a waist of <strong>B</strong>s resources. I need a way for when <strong>C</strong> makes a change for the socket to update <strong>B</strong>.</p>
  
  <p>This is the code for the socket:</p>
  
  <pre><code>&lt;?php
  namespace Notify;
  use Ratchet\MessageComponentInterface;
  use Ratchet\ConnectionInterface;
  
  require "/NAS/notify/db.php";
  
  class Note implements MessageComponentInterface { 
      protected $clients;
  
      public function __construct() {
          $this-&gt;clients = new \SplObjectStorage;
      }
  
      public function onOpen(ConnectionInterface $conn) {
          $this-&gt;clients-&gt;attach($conn);
      }
  
      public function onMessage(ConnectionInterface $from, $msg) {
          $stack = array(); 
          foreach ($this-&gt;clients as $client) {
              if ($from === $client) { //current client only
                  $query = getNotifications($msg);
                  if($query){
                      while($row = mysqli_fetch_assoc($query)){
                          array_push($stack, $row);
                          deleteNotification($row['id'], $msg);
                      }
                      $client-&gt;send(json_encode($stack));
                  }
              }
          }
      }
  
      public function onClose(ConnectionInterface $conn) {
          $this-&gt;clients-&gt;detach($conn);
      }
  
      public function onError(ConnectionInterface $conn, \Exception $e) {
          $conn-&gt;close();
      }
  }
  </code></pre>
  
  <p>Where <code>getNotifications()</code> gets the change in the database and <code>deleteNotification()</code> deletes it.</p>
  
  <hr>
  
  <p>Ideas:</p>
  
  <ol>
  <li>I have thought about storing the <code>$client</code> object in a database so that when <strong>C</strong> makes the change it can use <code>$client-&gt;send()</code> but I do not think that is possible? </li>
  <li>I could have a <code>while(true)</code> loop with the <code>$query = getNotifications($msg);</code> code inside - awful for <strong>A</strong>.</li>
  </ol>
  
  <p>Do you have any other ideas? Or ways to implement the above.</p>