Permalink
Browse files

use a dsn to connect to redis, and support redis auth

1 parent 3187b58 commit 133c2627d3822b1820de60c24488f05eae563aba @jdp committed Mar 20, 2012
Showing with 80 additions and 114 deletions.
  1. +13 −19 LICENSE
  2. +33 −45 README.markdown
  3. +34 −50 redisent.php
View
32 LICENSE
@@ -1,22 +1,16 @@
-Copyright (c) 2009 Justin Poliey <jdp34@njit.edu>
+ISC License
+http://www.opensource.org/licenses/ISC
-Permission is hereby granted, free of charge, to any person
-obtaining a copy of this software and associated documentation
-files (the "Software"), to deal in the Software without
-restriction, including without limitation the rights to use,
-copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the
-Software is furnished to do so, subject to the following
-conditions:
+Copyright (c) 2009-2012 Justin Poliey <justin@getglue.com>
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
-HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-OTHER DEALINGS IN THE SOFTWARE.
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
View
@@ -1,67 +1,55 @@
# Redisent
-Redisent is a simple, no-nonsense interface to the [Redis](http://code.google.com/p/redis/) key-value store for modest developers.
+Redisent is a simple, no-nonsense interface to the [Redis](http://redis.io) key-value store for modest developers.
Due to the way it is implemented, it is flexible and tolerant of changes to the Redis protocol.
-## Getting to work
+## Introduction
If you're at all familiar with the Redis protocol and PHP objects, you've already mastered Redisent.
All Redisent does is map the Redis protocol to a PHP object, abstract away the nitty-gritty, and make the return values PHP compatible.
- require 'redisent.php';
- $redis = new redisent\Redis('localhost');
- $redis->set('awesome', 'absolutely');
- echo sprintf('Is Redisent awesome? %s.\n', $redis->get('awesome'));
+``` php
+require 'redisent.php';
-You use the exact same command names, and the exact same argument order. **How wonderful.** How about a more complex example?
+$redis = new redisent\Redis('redis://localhost');
+$redis->set('awesome', 'absolutely');
+echo sprintf('Is Redisent awesome? %s.\n', $redis->get('awesome'));
+```
- require 'redisent.php';
- $redis = new redisent\Redis('localhost');
- $redis->rpush('particles', 'proton');
- $redis->rpush('particles', 'electron');
- $redis->rpush('particles', 'neutron');
- $particles = $redis->lrange('particles', 0, -1);
- $particle_count = $redis->llen('particles');
- echo "<p>The {$particle_count} particles that make up atoms are:</p>";
- echo "<ul>";
- foreach ($particles as $particle) {
- echo "<li>{$particle}</li>";
- }
- echo "</ul>";
+Redisent takes advantage of the [Unified Protocol](http://redis.io/topics/protocol) to be resilient to changes to the Redis command set.
-Be aware that Redis error responses will be wrapped in a RedisException class and thrown, so do be sure to use proper coding techniques.
+``` php
+require 'redisent.php';
-## Clustering your servers
+$redis = new redisent\Redis();
+$redis->rpush('particles', 'proton');
+$redis->rpush('particles', 'electron');
+$redis->rpush('particles', 'neutron');
+$particles = $redis->lrange('particles', 0, -1);
+$particle_count = $redis->llen('particles');
-Redisent also includes a way for developers to fully utilize the scalability of Redis with multiple servers and [consistent hashing](http://en.wikipedia.org/wiki/Consistent_hashing).
-Using the RedisentCluster class, you can use Redisent the same way, except that keys will be hashed across multiple servers.
-Here is how to set up a cluster:
+echo "<p>The {$particle_count} particles that make up atoms are:</p>";
+echo "<ul>";
+foreach ($particles as $particle) {
+ echo "<li>{$particle}</li>";
+}
+echo "</ul>";
+```
- include 'redisent_cluster.php';
+Redis error replies will be wrapped in a `RedisException` and thrown.
- $cluster = new RedisentCluster(array(
- array('host' => '127.0.0.1', 'port' => 6379),
- array('host' => '127.0.0.1', 'port' => 6380)
- ));
+## Implementation
-You can then use Redisent the way you normally would, i.e., `$cluster->set('key', 'value')` or `$cluster->lrange('particles', 0, -1)`.
-But what about when you need to use commands that are server specific and do not operate on keys? You can use routing, with the `RedisentCluster::to` method.
-To use routing, you need to assign a server an alias in the constructor of the Redis cluster. Aliases are not required on all servers, just the ones you want to be able to access directly.
+Behind the scenes, method calls to a `Redis` instance go through the `[__call](http://us3.php.net/manual/en/language.oop5.overloading.php#object.call)` magic method. The Unified Protocol command is then generated and sent to the Redis server, and the response is returned.
- include 'redisent_cluster.php';
-
- $cluster = new RedisentCluster(array(
- 'alpha' => array('host' => '127.0.0.1', 'port' => 6379),
- array('host' => '127.0.0.1', 'port' => 6380)
- ));
+## About
-Now there is an alias of the server running on 127.0.0.1:6379 called **alpha**, and can be interacted with like this:
+&copy; 2009-2012 [Justin Poliey](http://justinpoliey.com)
- // get server info
- $cluster->to('alpha')->info();
+## [License](http://www.opensource.org/licenses/ISC)
-Now you have complete programatic control over your Redis servers.
+Copyright (c) 2009-2012 Justin Poliey <justin@getglue.com>
-## About
+Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
-&copy; 2009 [Justin Poliey](http://justinpoliey.com)
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
View
@@ -1,9 +1,9 @@
<?php
/**
* Redisent, a Redis interface for the modest
- * @author Justin Poliey <jdp34@njit.edu>
- * @copyright 2009 Justin Poliey <jdp34@njit.edu>
- * @license http://www.opensource.org/licenses/mit-license.php The MIT License
+ * @author Justin Poliey <justin@getglue.com>
+ * @copyright 2009-2012 Justin Poliey <justin@getglue.com>
+ * @license http://www.opensource.org/licenses/ISC The ISC License
* @package Redisent
*/
@@ -30,31 +30,28 @@ class Redis {
private $__sock;
/**
- * Host of the Redis server
- * @var string
+ * The structure representing the data source of the Redis server
+ * @var array
* @access public
*/
- public $host;
+ public $dsn;
/**
- * Port on which the Redis server is running
- * @var integer
- * @access public
- */
- public $port;
-
- /**
- * Creates a Redisent connection to the Redis server on host {@link $host} and port {@link $port}.
- * @param string $host The hostname of the Redis server
- * @param integer $port The port number of the Redis server
+ * Creates a Redisent connection to the Redis server at the address specified by {@link $dsn}.
+ * The default connection is to the server running on localhost on port 6379.
+ * @param string $dsn The data source name of the Redis server
*/
- function __construct($host, $port = 6379) {
- $this->host = $host;
- $this->port = $port;
- $this->__sock = @fsockopen($this->host, $this->port, $errno, $errstr);
- if (!$this->__sock) {
+ function __construct($dsn = 'redis://localhost:6379') {
+ $this->dsn = parse_url($dsn);
+ $host = isset($this->dsn['host']) ? $this->dsn['host'] : 'localhost';
+ $port = isset($this->dsn['port']) ? $this->dsn['port'] : 6379;
+ $this->__sock = @fsockopen($host, $port, $errno, $errstr);
+ if ($this->__sock === FALSE) {
throw new \Exception("{$errno} - {$errstr}");
}
+ if (isset($this->dsn['pass'])) {
+ $this->auth($this->dsn['pass']);
+ }
}
function __destruct() {
@@ -77,30 +74,37 @@ function __call($name, $args) {
}
}
+ return $this->readResponse();
+ }
+
+ private function readResponse() {
/* Parse the response based on the reply identifier */
$reply = trim(fgets($this->__sock, 512));
switch (substr($reply, 0, 1)) {
/* Error reply */
case '-':
- throw new RedisException(substr(trim($reply), 4));
+ throw new RedisException(trim(substr($reply, 4)));
break;
/* Inline reply */
case '+':
$response = substr(trim($reply), 1);
+ if ($response === 'OK') {
+ $response = TRUE;
+ }
break;
/* Bulk reply */
case '$':
- $response = null;
+ $response = NULL;
if ($reply == '$-1') {
break;
}
$read = 0;
- $size = substr($reply, 1);
- if ($size > 0){
+ $size = intval(substr($reply, 1));
+ if ($size > 0) {
do {
$block_size = ($size - $read) > 1024 ? 1024 : ($size - $read);
$r = fread($this->__sock, $block_size);
- if ($r === false) {
+ if ($r === FALSE) {
throw new \Exception('Failed to read response from stream');
} else {
$read += strlen($r);
@@ -112,41 +116,21 @@ function __call($name, $args) {
break;
/* Multi-bulk reply */
case '*':
- $count = substr($reply, 1);
+ $count = intval(substr($reply, 1));
if ($count == '-1') {
- return null;
+ return NULL;
}
$response = array();
for ($i = 0; $i < $count; $i++) {
- $bulk_head = trim(fgets($this->__sock, 512));
- $size = substr($bulk_head, 1);
- if ($size == '-1') {
- $response[] = null;
- }
- else {
- $read = 0;
- $block = "";
- do {
- $block_size = ($size - $read) > 1024 ? 1024 : ($size - $read);
- $r = fread($this->__sock, $block_size);
- if ($r === false) {
- throw new \Exception('Failed to read response from stream');
- } else {
- $read += strlen($r);
- $block .= $r;
- }
- } while ($read < $size);
- fread($this->__sock, 2); /* discard crlf */
- $response[] = $block;
- }
+ $response[] = $this->readResponse();
}
break;
/* Integer reply */
case ':':
$response = intval(substr(trim($reply), 1));
break;
default:
- throw new RedisException("invalid server response: {$reply}");
+ throw new RedisException("Unknown response: {$reply}");
break;
}
/* Party on */

0 comments on commit 133c262

Please sign in to comment.