Browse Source

Implemented the new Predis\MultiExecBlock class to wrap commands issued inside of MULTI + EXEC.

Daniele Alessandri 15 years ago
parent
commit
f4b0f664e7
1 changed files with 53 additions and 0 deletions
  1. 53 0
      lib/Predis.php

+ 53 - 0
lib/Predis.php

@@ -445,6 +445,59 @@ class CommandPipeline {
     }
 }
 
+class MultiExecBlock {
+    private $_redisClient, $_commands, $_initialized;
+
+    public function __construct(Client $redisClient) {
+        $this->_initialized = false;
+        $this->_redisClient = $redisClient;
+        $this->_commands    = array();
+    }
+
+    private function initialize() {
+        if ($this->_initialized === false) {
+            $this->_redisClient->multi();
+            $this->_initialized = true;
+        }
+    }
+
+    public function __call($method, $arguments) {
+        $this->initialize();
+        $command = $this->_redisClient->createCommand($method, $arguments);
+        if ($this->_redisClient->executeCommand($command) === 'QUEUED') {
+            $this->_commands[] = $command;
+        }
+        else {
+            // TODO: ...
+            throw ClientException('Unexpected condition');
+        }
+    }
+
+    public function execute(\Closure $block = null) {
+        $blockException = null;
+        $returnValues   = array();
+
+        try {
+            if ($block !== null) {
+                $block($this);
+            }
+            $execReply = $this->_redisClient->exec();
+            for ($i = 0; $i < count($execReply); $i++) {
+                $returnValues[] = $this->_commands[$i]->parseResponse($execReply[$i]);
+            }
+        }
+        catch (\Exception $exception) {
+            $blockException = $exception;
+        }
+
+        if ($blockException !== null) {
+            throw $blockException;
+        }
+
+        return $returnValues;
+    }
+}
+
 /* ------------------------------------------------------------------------- */
 
 class ConnectionParameters {