DispatcherLoop.php 2.0 KB

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