Ver Fonte

Update examples.

Daniele Alessandri há 11 anos atrás
pai
commit
3c77d3b0c1

+ 7 - 14
examples/CustomDistributionStrategy.php

@@ -19,25 +19,21 @@ use Predis\Connection\PredisCluster;
 use Predis\Cluster\Distributor\DistributorInterface;
 use Predis\Cluster\Hash\HashGeneratorInterface;
 
-class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
-{
+class NaiveDistributor implements DistributorInterface, HashGeneratorInterface {
     private $nodes;
     private $nodesCount;
 
-    public function __construct()
-    {
+    public function __construct() {
         $this->nodes = array();
         $this->nodesCount = 0;
     }
 
-    public function add($node, $weight = null)
-    {
+    public function add($node, $weight = null) {
         $this->nodes[] = $node;
         $this->nodesCount++;
     }
 
-    public function remove($node)
-    {
+    public function remove($node) {
         $this->nodes = array_filter($this->nodes, function ($n) use ($node) {
             return $n !== $node;
         });
@@ -45,8 +41,7 @@ class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
         $this->nodesCount = count($this->nodes);
     }
 
-    public function get($key)
-    {
+    public function get($key) {
         if (0 === $count = $this->nodesCount) {
             throw new RuntimeException('No connections');
         }
@@ -54,13 +49,11 @@ class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
         return $this->nodes[$count > 1 ? abs($key % $count) : 0];
     }
 
-    public function hash($value)
-    {
+    public function hash($value) {
         return crc32($value);
     }
 
-    public function getHashGenerator()
-    {
+    public function getHashGenerator() {
         return $this;
     }
 }

+ 8 - 13
examples/DispatcherLoop.php

@@ -31,27 +31,22 @@ $client = new Predis\Client($single_server + array('read_write_timeout' => 0));
 $dispatcher = new Predis\PubSub\DispatcherLoop($client);
 
 // Demonstrate how to use a callable class as a callback for Predis\DispatcherLoop.
-class EventsListener implements Countable
-{
+class EventsListener implements Countable {
     private $events;
 
-    public function __construct()
-    {
+    public function __construct() {
         $this->events = array();
     }
 
-    public function count()
-    {
+    public function count() {
         return count($this->events);
     }
 
-    public function getEvents()
-    {
+    public function getEvents() {
         return $this->events;
     }
 
-    public function __invoke($payload)
-    {
+    public function __invoke($payload) {
         $this->events[] = $payload;
     }
 }
@@ -71,8 +66,8 @@ $dispatcher->attachCallback('control', function ($payload) use ($dispatcher) {
 $dispatcher->run();
 
 // Display our achievements!
-echo "We received {$events->count()} messages!\n";
+echo "We received {$events->count()} messages!", PHP_EOL;
 
 // Say goodbye :-)
-$info = $client->info();
-print_r("Goodbye from Redis v{$info['redis_version']}!\n");
+$version = redis_version($client->info());
+echo "Goodbye from Redis $version!", PHP_EOL;

+ 10 - 10
examples/KeyPrefixes.php

@@ -20,18 +20,18 @@ require 'SharedConfigurations.php';
 $client = new Predis\Client($single_server, array('prefix' => 'nrk:'));
 
 $client->mset(array('foo' => 'bar', 'lol' => 'wut'));
-var_dump($client->mget('foo', 'lol'));
+var_export($client->mget('foo', 'lol'));
 /*
-array(2) {
-  [0]=> string(3) "bar"
-  [1]=> string(3) "wut"
-}
+array (
+  0 => 'bar',
+  1 => 'wut',
+)
 */
 
-var_dump($client->keys('*'));
+var_export($client->keys('*'));
 /*
-array(2) {
-  [0]=> string(7) "nrk:foo"
-  [1]=> string(7) "nrk:lol"
-}
+array (
+  0 => 'nrk:foo',
+  1 => 'nrk:lol',
+)
 */

+ 4 - 4
examples/MasterSlaveReplication.php

@@ -33,20 +33,20 @@ $client = new Predis\Client($parameters, $options);
 // Read operation.
 $exists = $client->exists('foo') ? 'yes' : 'no';
 $current = $client->getConnection()->getCurrent()->getParameters();
-echo "Does 'foo' exist on {$current->alias}? $exists.\n";
+echo "Does 'foo' exist on {$current->alias}? $exists.", PHP_EOL;
 
 // Write operation.
 $client->set('foo', 'bar');
 $current = $client->getConnection()->getCurrent()->getParameters();
-echo "Now 'foo' has been set to 'bar' on {$current->alias}!\n";
+echo "Now 'foo' has been set to 'bar' on {$current->alias}!", PHP_EOL;
 
 // Read operation.
 $bar = $client->get('foo');
 $current = $client->getConnection()->getCurrent()->getParameters();
-echo "We just fetched 'foo' from {$current->alias} and its value is '$bar'.\n";
+echo "We fetched 'foo' from {$current->alias} and its value is '$bar'.", PHP_EOL;
 
 /* OUTPUT:
 Does 'foo' exist on slave? yes.
 Now 'foo' has been set to 'bar' on master!
-We just fetched 'foo' from master and its value is 'bar'.
+We fetched 'foo' from master and its value is 'bar'.
 */

+ 3 - 3
examples/MasterSlaveReplicationComplex.php

@@ -28,14 +28,14 @@ use Predis\Replication\ReplicationStrategy;
 // of hashes with a single roundtrip.
 
 class HashMultipleGetAll extends ScriptCommand {
-    const BODY = <<<EOS
+    const BODY = <<<LUA
 local hashes = {}
 for _, key in pairs(KEYS) do
     table.insert(hashes, key)
     table.insert(hashes, redis.call('hgetall', key))
 end
 return hashes
-EOS;
+LUA;
 
     public function getScript() {
         return self::BODY;
@@ -79,5 +79,5 @@ $hashes = $client->hmgetall('metavars', 'servers');
 $replication = $client->getConnection();
 $stillOnSlave = $replication->getCurrent() === $replication->getConnectionById('slave');
 
-echo "Is still on slave? ", $stillOnSlave ? 'YES' : 'NO', "!\n";
+echo "Is still on slave? ", $stillOnSlave ? 'YES!' : 'NO!', PHP_EOL;
 var_export($hashes);

+ 5 - 5
examples/MonitorConsumer.php

@@ -28,17 +28,17 @@ foreach (($monitor = $client->monitor()) as $event) {
     // If we notice a ECHO command with the message QUIT_MONITOR, we stop the
     // monitor consumer and then break the loop.
     if ($event->command === 'ECHO' && $event->arguments === '"QUIT_MONITOR"') {
-        echo "Exiting the monitor loop...\n";
+        echo "Exiting the monitor loop...", PHP_EOL;
         $monitor->stop();
         break;
     }
 
-    echo "* Received {$event->command} on DB {$event->database} at {$timestamp->format(DateTime::W3C)}\n";
+    echo "* Received {$event->command} on DB {$event->database} at {$timestamp->format(DateTime::W3C)}", PHP_EOL;
     if (isset($event->arguments)) {
-        echo "    Arguments: {$event->arguments}\n";
+        echo "    Arguments: {$event->arguments}", PHP_EOL;
     }
 }
 
 // Say goodbye :-)
-$info = $client->info();
-print_r("Goodbye from Redis v{$info['redis_version']}!\n");
+$version = redis_version($client->info());
+echo "Goodbye from Redis $version!", PHP_EOL;

+ 5 - 6
examples/MultipleSetAndGet.php

@@ -26,13 +26,12 @@ $client = new Predis\Client($single_server);
 $client->mset($mkv);
 $retval = $client->mget(array_keys($mkv));
 
-print_r($retval);
+var_export($retval);
 
 /* OUTPUT:
-Array
-(
-    [0] => First user
-    [1] => Second user
-    [2] => Third user
+array (
+  0 => 'First user',
+  1 => 'Second user',
+  2 => 'Third user',
 )
 */

+ 13 - 15
examples/PipeliningCommands.php

@@ -27,22 +27,20 @@ $replies = $client->pipeline(function ($pipe) {
     $pipe->mget('does_not_exist', 'counter');
 });
 
-print_r($replies);
+var_export($replies);
 
 /* OUTPUT:
-Array
-(
-    [0] => 1
-    [1] => 1
-    [2] => 10
-    [3] => 40
-    [4] => 1
-    [5] => 40
-    [6] => Array
-        (
-            [0] =>
-            [1] => 40
-        )
-
+array (
+  0 => true,
+  1 => true,
+  2 => 10,
+  3 => 40,
+  4 => true,
+  5 => '40',
+  6 =>
+  array (
+    0 => NULL,
+    1 => '40',
+  ),
 )
 */

+ 7 - 7
examples/PubSubConsumer.php

@@ -30,20 +30,20 @@ $pubsub->subscribe('control_channel', 'notifications');
 foreach ($pubsub as $message) {
     switch ($message->kind) {
         case 'subscribe':
-            echo "Subscribed to {$message->channel}\n";
+            echo "Subscribed to {$message->channel}", PHP_EOL;
             break;
 
         case 'message':
             if ($message->channel == 'control_channel') {
                 if ($message->payload == 'quit_loop') {
-                    echo "Aborting pubsub loop...\n";
+                    echo "Aborting pubsub loop...", PHP_EOL;
                     $pubsub->unsubscribe();
                 } else {
-                    echo "Received an unrecognized command: {$message->payload}.\n";
+                    echo "Received an unrecognized command: {$message->payload}.", PHP_EOL;
                 }
             } else {
-                echo "Received the following message from {$message->channel}:\n",
-                     "  {$message->payload}\n\n";
+                echo "Received the following message from {$message->channel}:",
+                     PHP_EOL, "  {$message->payload}", PHP_EOL, PHP_EOL;
             }
             break;
     }
@@ -55,5 +55,5 @@ foreach ($pubsub as $message) {
 unset($pubsub);
 
 // Say goodbye :-)
-$info = $client->info();
-print_r("Goodbye from Redis v{$info['redis_version']}!\n");
+$version = redis_version($client->info());
+echo "Goodbye from Redis $version!", PHP_EOL;

+ 8 - 4
examples/ServerSideScripting.php

@@ -32,8 +32,7 @@ class IncrementExistingKeysBy extends ScriptCommand
 
     public function getScript()
     {
-        return
-<<<LUA
+        return <<<LUA
 local cmd, insert = redis.call, table.insert
 local increment, results = ARGV[1], { }
 
@@ -50,9 +49,14 @@ LUA;
     }
 }
 
-$client = new Predis\Client($single_server);
+$client = new Predis\Client($single_server, array(
+    'profile' => function ($options) {
+        $profile = $options->getDefault('profile');
+        $profile->defineCommand('increxby', 'IncrementExistingKeysBy');
 
-$client->getProfile()->defineCommand('increxby', 'IncrementExistingKeysBy');
+        return $profile;
+    }
+));
 
 $client->mset('foo', 10, 'foobar', 100);
 

+ 2 - 2
examples/SessionHandler.php

@@ -32,8 +32,8 @@ session_id('example_session_id');
 session_start();
 
 if (isset($_SESSION['foo'])) {
-    echo "Session has `foo` set to {$_SESSION['foo']}\n";
+    echo "Session has `foo` set to {$_SESSION['foo']}", PHP_EOL;
 } else {
     $_SESSION['foo'] = $value = mt_rand();
-    echo "Empty session, `foo` has been set with $value\n";
+    echo "Empty session, `foo` has been set with $value", PHP_EOL;
 }

+ 11 - 0
examples/SharedConfigurations.php

@@ -11,6 +11,17 @@
 
 require __DIR__.'/../autoload.php';
 
+function redis_version($info)
+{
+    if (isset($info['Server']['redis_version'])) {
+        return $info['Server']['redis_version'];
+    } else if (isset($info['redis_version'])) {
+        return $info['Server']['redis_version'];
+    } else {
+        return 'unknown version';
+    }
+}
+
 $single_server = array(
     'host'     => '127.0.0.1',
     'port'     => 6379,

+ 18 - 25
examples/SimpleDebuggableConnection.php

@@ -14,20 +14,17 @@ require 'SharedConfigurations.php';
 use Predis\Command\CommandInterface;
 use Predis\Connection\StreamConnection;
 
-class SimpleDebuggableConnection extends StreamConnection
-{
+class SimpleDebuggableConnection extends StreamConnection {
     private $tstart = 0;
     private $debugBuffer = array();
 
-    public function connect()
-    {
+    public function connect() {
         $this->tstart = microtime(true);
 
         parent::connect();
     }
 
-    private function storeDebug(CommandInterface $command, $direction)
-    {
+    private function storeDebug(CommandInterface $command, $direction) {
         $firtsArg  = $command->getArgument(0);
         $timestamp = round(microtime(true) - $this->tstart, 4);
 
@@ -39,23 +36,20 @@ class SimpleDebuggableConnection extends StreamConnection
         $this->debugBuffer[] = $debug;
     }
 
-    public function writeCommand(CommandInterface $command)
-    {
+    public function writeCommand(CommandInterface $command) {
         parent::writeCommand($command);
 
         $this->storeDebug($command, '->');
     }
 
-    public function readResponse(CommandInterface $command)
-    {
-        $reply = parent::readResponse($command);
+    public function readResponse(CommandInterface $command) {
+        $response = parent::readResponse($command);
         $this->storeDebug($command, '<-');
 
-        return $reply;
+        return $response;
     }
 
-    public function getDebugBuffer()
-    {
+    public function getDebugBuffer() {
         return $this->debugBuffer;
     }
 }
@@ -71,18 +65,17 @@ $client->set('foo', 'bar');
 $client->get('foo');
 $client->info();
 
-print_r($client->getConnection()->getDebugBuffer());
+var_export($client->getConnection()->getDebugBuffer());
 
 /* OUTPUT:
-Array
-(
-    [0] => SELECT 15 -> 127.0.0.1:6379 [0.0008s]
-    [1] => SELECT 15 <- 127.0.0.1:6379 [0.0012s]
-    [2] => SET foo -> 127.0.0.1:6379 [0.0014s]
-    [3] => SET foo <- 127.0.0.1:6379 [0.0014s]
-    [4] => GET foo -> 127.0.0.1:6379 [0.0016s]
-    [5] => GET foo <- 127.0.0.1:6379 [0.0018s]
-    [6] => INFO -> 127.0.0.1:6379 [0.002s]
-    [7] => INFO <- 127.0.0.1:6379 [0.0025s]
+array (
+  0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
+  1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
+  2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
+  3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
+  4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
+  5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
+  6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
+  7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
 )
 */

+ 2 - 2
examples/SimpleSetAndGet.php

@@ -18,8 +18,8 @@ $client = new Predis\Client($single_server);
 $client->set('library', 'predis');
 $retval = $client->get('library');
 
-var_dump($retval);
+var_export($retval);
 
 /* OUTPUT
-string(6) "predis"
+'predis'
 */

+ 4 - 1
examples/TransactionWithCAS.php

@@ -22,6 +22,9 @@ require 'SharedConfigurations.php';
 // ZADD zset 1 a
 // ZADD zset 2 b
 // ZADD zset 3 c
+//
+// Then execute this script four times and see its output.
+//
 
 function zpop($client, $key)
 {
@@ -48,4 +51,4 @@ function zpop($client, $key)
 $client = new Predis\Client($single_server);
 $zpopped = zpop($client, 'zset');
 
-echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "\n";
+echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", PHP_EOL;