dispatcher_loop.php 2.0 KB

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