Project

General

Profile

1
<?php
2

    
3
/*
4
 * This file is part of the Predis package.
5
 *
6
 * (c) Daniele Alessandri <suppakilla@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

    
12
require 'SharedConfigurations.php';
13

    
14
/*
15
This is a basic example on how to use the Predis\DispatcherLoop class.
16

    
17
To see this example in action you can just use redis-cli and publish some
18
messages to the 'events' and 'control' channel, e.g.:
19

    
20
./redis-cli
21
PUBLISH events first
22
PUBLISH events second
23
PUBLISH events third
24
PUBLISH control terminate_dispatcher
25
*/
26

    
27
// Create a client and disable r/w timeout on the socket
28
$client = new Predis\Client($single_server + array('read_write_timeout' => 0));
29

    
30
// Create a Predis\DispatcherLoop instance and attach a bunch of callbacks.
31
$dispatcher = new Predis\PubSub\DispatcherLoop($client);
32

    
33
// Demonstrate how to use a callable class as a callback for Predis\DispatcherLoop.
34
class EventsListener implements Countable
35
{
36
    private $events;
37

    
38
    public function __construct()
39
    {
40
        $this->events = array();
41
    }
42

    
43
    public function count()
44
    {
45
        return count($this->events);
46
    }
47

    
48
    public function getEvents()
49
    {
50
        return $this->events;
51
    }
52

    
53
    public function __invoke($payload)
54
    {
55
        $this->events[] = $payload;
56
    }
57
}
58

    
59
// Attach our callable class to the dispatcher.
60
$dispatcher->attachCallback('events', ($events = new EventsListener()));
61

    
62
// Attach a function to control the dispatcher loop termination with a message.
63
$dispatcher->attachCallback('control', function ($payload) use ($dispatcher) {
64
    if ($payload === 'terminate_dispatcher') {
65
        $dispatcher->stop();
66
    }
67
});
68

    
69
// Run the dispatcher loop until the callback attached to the 'control' channel
70
// receives 'terminate_dispatcher' as a message.
71
$dispatcher->run();
72

    
73
// Display our achievements!
74
echo "We received {$events->count()} messages!\n";
75

    
76
// Say goodbye :-)
77
$info = $client->info();
78
print_r("Goodbye from Redis v{$info['redis_version']}!\n");
(2-2/17)