Romanovich095

CakePHP 3.x Socket component with Elephant.IO for NodeJS

Aug 26th, 2016
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.22 KB | None | 0 0
  1. <?php
  2. namespace App\Controller\Component;
  3.  
  4. use Cake\Controller\Component;
  5. use Cake\Core\Configure;
  6. use Cake\Log\Log;
  7. use ElephantIO\Client as Client;
  8. use ElephantIO\Engine\SocketIO\Version1X as Version;
  9.  
  10. /**
  11.  * Class SocketComponent
  12.  * @package App\Controller\Component
  13.  */
  14. class SocketComponent extends Component
  15. {
  16.  
  17.     /**
  18.      * Sockets client
  19.      *
  20.      * @var Client
  21.      */
  22.     private $_sender;
  23.  
  24.     /**
  25.      * Sockets connection url
  26.      *
  27.      * @var string
  28.      */
  29.     private $_url;
  30.  
  31.     /**
  32.      * Building up a connection to socket
  33.      *
  34.      * @param array $config
  35.      */
  36.     public function initialize(array $config)
  37.     {
  38.         $this->_url = Configure::read('socket_url');
  39.         $this->_sender = new Client(new Version($this->_url));
  40.         $this->_sender->initialize();
  41.     }
  42.  
  43.     /**
  44.      * Sending data
  45.      *
  46.      * @param string $key
  47.      * @param array $data
  48.      */
  49.     public function emit($key = 'broadcast', $data = [])
  50.     {
  51.         Log::info($data + ['user' => $key]);
  52.         $this->_sender->emit($key, (array)$data);
  53.     }
  54.  
  55.     /**
  56.      * Closing connection
  57.      */
  58.     public function __destruct()
  59.     {
  60.         $this->_sender->close();
  61.     }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment