PubSubContext.php 1.7 KB

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