DispatcherLoop.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. {
  20. private $_events;
  21. public function __construct()
  22. {
  23. $this->_events = array();
  24. }
  25. public function count()
  26. {
  27. return count($this->_events);
  28. }
  29. public function getEvents()
  30. {
  31. return $this->_events;
  32. }
  33. public function __invoke($payload)
  34. {
  35. $this->_events[] = $payload;
  36. }
  37. }
  38. // Attach our callable class to the dispatcher.
  39. $dispatcher->attachCallback('events', ($events = new EventsListener()));
  40. // Attach a function to control the dispatcher loop termination with a message.
  41. $dispatcher->attachCallback('control', function($payload) use ($dispatcher) {
  42. if ($payload === 'terminate_dispatcher') {
  43. $dispatcher->stop();
  44. }
  45. });
  46. // Run the dispatcher loop until the callback attached to the 'control' channel
  47. // receives 'terminate_dispatcher' as a message.
  48. $dispatcher->run();
  49. // Display our achievements!
  50. echo "We received {$events->count()} messages!\n";
  51. // Say goodbye :-)
  52. $info = $client->info();
  53. print_r("Goodbye from Redis v{$info['redis_version']}!\n");