dispatcher_loop.php 2.1 KB

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