PubSubContext.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. } else {
  34. echo "Received an unrecognized command: {$message->payload}.\n";
  35. }
  36. } else {
  37. echo "Received the following message from {$message->channel}:\n",
  38. " {$message->payload}\n\n";
  39. }
  40. break;
  41. }
  42. }
  43. // Always unset the pubsub context instance when you are done! The
  44. // class destructor will take care of cleanups and prevent protocol
  45. // desynchronizations between the client and the server.
  46. unset($pubsub);
  47. // Say goodbye :-)
  48. $info = $client->info();
  49. print_r("Goodbye from Redis v{$info['redis_version']}!\n");