PubSubContext.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. require_once '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->pubSubContext();
  9. // Subscribe to your channels
  10. $pubsub->subscribe('control_channel');
  11. $pubsub->subscribe('notifications');
  12. // Start processing the pubsup messages. Open a terminal and use redis-cli
  13. // to push messages to the channels. Examples:
  14. // ./redis-cli PUBLISH notifications "this is a test"
  15. // ./redis-cli PUBLISH control_channel quit_loop
  16. foreach ($pubsub as $message) {
  17. switch ($message->kind) {
  18. case 'subscribe':
  19. echo "Subscribed to {$message->channel}\n";
  20. break;
  21. case 'message':
  22. if ($message->channel == 'control_channel') {
  23. if ($message->payload == 'quit_loop') {
  24. echo "Aborting pubsub loop...\n";
  25. $pubsub->unsubscribe();
  26. }
  27. else {
  28. echo "Received an unrecognized command: {$message->payload}.\n";
  29. }
  30. }
  31. else {
  32. echo "Received the following message from {$message->channel}:\n",
  33. " {$message->payload}\n\n";
  34. }
  35. break;
  36. }
  37. }
  38. // Always unset the pubsub context instance when you are done! The
  39. // class destructor will take care of cleanups and prevent protocol
  40. // desynchronizations between the client and the server.
  41. unset($pubsub);
  42. // Say goodbye :-)
  43. $info = $redis->info();
  44. print_r("Goodbye from Redis v{$info['redis_version']}!\n");
  45. ?>