DispatcherLoop.php 2.0 KB

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