dispatcher_loop.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 __DIR__.'/shared.php';
  11. // This is a basic example on how to use the Predis\DispatcherLoop class.
  12. //
  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. // Create a client and disable r/w timeout on the socket
  21. $client = new Predis\Client($single_server + array('read_write_timeout' => 0));
  22. // Create a Predis\DispatcherLoop instance and attach a bunch of callbacks.
  23. $dispatcher = new Predis\PubSub\DispatcherLoop($client);
  24. // Demonstrate how to use a callable class as a callback for Predis\DispatcherLoop.
  25. class EventsListener implements Countable
  26. {
  27. private $events;
  28. public function __construct()
  29. {
  30. $this->events = array();
  31. }
  32. public function count()
  33. {
  34. return count($this->events);
  35. }
  36. public function getEvents()
  37. {
  38. return $this->events;
  39. }
  40. public function __invoke($payload)
  41. {
  42. $this->events[] = $payload;
  43. }
  44. }
  45. // Attach our callable class to the dispatcher.
  46. $dispatcher->attachCallback('events', ($events = new EventsListener()));
  47. // Attach a function to control the dispatcher loop termination with a message.
  48. $dispatcher->attachCallback('control', function ($payload) use ($dispatcher) {
  49. if ($payload === 'terminate_dispatcher') {
  50. $dispatcher->stop();
  51. }
  52. });
  53. // Run the dispatcher loop until the callback attached to the 'control' channel
  54. // receives 'terminate_dispatcher' as a message.
  55. $dispatcher->run();
  56. // Display our achievements!
  57. echo "We received {$events->count()} messages!", PHP_EOL;
  58. // Say goodbye :-)
  59. $version = redis_version($client->info());
  60. echo "Goodbye from Redis $version!", PHP_EOL;