Rediska

Follow me on twitter…

Publish/Subscribe

Public/Subscribe messaging paradigm implementation:

<?php

// Initialize Rediska
$rediska = new Rediska();

// Subscribe to 'channel'
$channel = $rediska->subscribe('channel');

// Gets messages in an endless loop
foreach($channel as $message) {
    print $message;

    // Exit from loop if needed
    if ($message == 'exit') {
        break;
    }
}

// Subscribe to few channels with timeout
$channels = $rediska->subscribe(array('channel', 'channel2'), 60);

// Gets messages for 1 minute and leaves the loop
foreach($channels as $channel => $message) {
    print "$channel: $message";

    // Unsubscribe from channels if needed
    if ($message == 'unsubscribe') {
        $channels->unsubscribe('channel2');
    }

    // Subscribe to channel if needed
    if ($message == 'subscribe') {
        $channels->subscribe('channel3');
    }
}

// Another way to subscribe to channel
$channel = new Rediska_PubSub_Channel('channel');
foreach($channel as $message) {
    print $message;
}

// Publish to channel
$channel[] = 'message';

// Other way to publish
$rediska = new Rediska();
$rediska->publish('channel', 'message');

// Or publish to few channels
$rediska->publish(array('channel', 'channel2'), 'message');

// Extend channel for you own model
class Chat extends Rediska_PubSub_Channel
{
    public function __construct()
    {
        parent::__construct('chat');
    }

    public function say($nick, $message)
    {
        $this->publish(array($nick, $message));
    }
}

// Read messages
$chat = new Chat();
foreach($chat as $nickAndMessage) {
    list($nick, $message) = $nickAndMessage;

    print "$nick say: $message";
}

// Write messages
$chat = new Chat();
$chat->say('John', 'Hello!');

?>

Comments

Fork me on GitHub