PubSubContext.php 1.6 KB

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