DispatcherLoop.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. require 'SharedConfigurations.php';
  3. /*
  4. This is a basic example on how to use the Predis\DispatcherLoop class.
  5. To see this example in action you can just use redis-cli and publish some
  6. messages to the 'events' and 'control' channel, e.g.:
  7. ./redis-cli
  8. PUBLISH events first
  9. PUBLISH events second
  10. PUBLISH events third
  11. PUBLISH control terminate_dispatcher
  12. */
  13. // Create a client and disable r/w timeout on the socket
  14. $client = new Predis\Client($single_server + array('read_write_timeout' => 0));
  15. // Create a Predis\DispatcherLoop instance and attach a bunch of callbacks.
  16. $dispatcher = new Predis\DispatcherLoop($client);
  17. // Demonstrate how to use a callable class as a callback for Predis\DispatcherLoop.
  18. class EventsListener implements Countable {
  19. private $_events;
  20. public function __construct() {
  21. $this->_events = array();
  22. }
  23. public function count() {
  24. return count($this->_events);
  25. }
  26. public function getEvents() {
  27. return $this->_events;
  28. }
  29. public function __invoke($payload) {
  30. $this->_events[] = $payload;
  31. }
  32. }
  33. // Attach our callable class to the dispatcher.
  34. $dispatcher->attachCallback('events', ($events = new EventsListener()));
  35. // Attach a function to control the dispatcher loop termination with a message.
  36. $dispatcher->attachCallback('control', function($payload) use ($dispatcher) {
  37. if ($payload === 'terminate_dispatcher') {
  38. $dispatcher->stop();
  39. }
  40. });
  41. // Run the dispatcher loop until the callback attached to the 'control' channel
  42. // receives 'terminate_dispatcher' as a message.
  43. $dispatcher->run();
  44. // Display our achievements!
  45. echo "We received {$events->count()} messages!\n";
  46. // Say goodbye :-)
  47. $info = $client->info();
  48. print_r("Goodbye from Redis v{$info['redis_version']}!\n");