PubSubContext.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // Redis 2.0 features new commands that allow clients to subscribe for
  12. // events published on certain channels (PUBSUB).
  13. // Create a client and disable r/w timeout on the socket
  14. $client = new Predis\Client($single_server + array('read_write_timeout' => 0));
  15. // Initialize a new pubsub context
  16. $pubsub = $client->pubSub();
  17. // Subscribe to your channels
  18. $pubsub->subscribe('control_channel', 'notifications');
  19. // Start processing the pubsup messages. Open a terminal and use redis-cli
  20. // to push messages to the channels. Examples:
  21. // ./redis-cli PUBLISH notifications "this is a test"
  22. // ./redis-cli PUBLISH control_channel quit_loop
  23. foreach ($pubsub as $message) {
  24. switch ($message->kind) {
  25. case 'subscribe':
  26. echo "Subscribed to {$message->channel}\n";
  27. break;
  28. case 'message':
  29. if ($message->channel == 'control_channel') {
  30. if ($message->payload == 'quit_loop') {
  31. echo "Aborting pubsub loop...\n";
  32. $pubsub->unsubscribe();
  33. }
  34. else {
  35. echo "Received an unrecognized command: {$message->payload}.\n";
  36. }
  37. }
  38. else {
  39. echo "Received the following message from {$message->channel}:\n",
  40. " {$message->payload}\n\n";
  41. }
  42. break;
  43. }
  44. }
  45. // Always unset the pubsub context instance when you are done! The
  46. // class destructor will take care of cleanups and prevent protocol
  47. // desynchronizations between the client and the server.
  48. unset($pubsub);
  49. // Say goodbye :-)
  50. $info = $client->info();
  51. print_r("Goodbye from Redis v{$info['redis_version']}!\n");