ci2.x版本,使用mongodb,需要安装pecl-php-mongo扩展(github上很多扩展已不可用,找到个可用版本纪录于此),添加到php.ini中
使用如下
public function index() { //var_dump($this->mongo_db->insert("task",array("uid"=>2,"name"=>"ciaos"))); //var_dump($this->mongo_db->get_where("task",array("uid"=>"ciaos"))); var_dump($this->mongo_db->where(array("uid"=>"ciaos"))->update("task",array("task.math"=>array(1,2)))); }
autoload.php增加redis,mongo_db自动加载
mongodb.php放到config目录下
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); // Generally will be localhost if you're querying from the machine that Mongo is installed on $config['mongo_host'] = "localhost"; // Generally will be 27017 unless you've configured Mongo otherwise $config['mongo_port'] = 27017; // The database you want to work from (required) $config['mongo_db'] = "dbname"; // Leave blank if Mongo is not running in auth mode $config['mongo_user'] = ""; $config['mongo_pass'] = ""; // Persistant connections $config['mongo_persist'] = TRUE; $config['mongo_persist_key'] = 'ci_mongo_persist'; // Get results as an object instead of an array $config['mongo_return'] = 'array'; // Set to object // When you run an insert/update/delete how sure do you want to be that the database has received the query? // safe = the database has receieved and executed the query // fysnc = as above + the change has been committed to harddisk <- NOTE: will introduce a performance penalty $config['mongo_query_safety'] = 'safe'; // Supress connection error password display $config['mongo_supress_connect_error'] = TRUE; // If you are having problems connecting try changing this to TRUE $config['host_db_flag'] = FALSE;
Mongo_db.php放到library下
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter MongoDB Active Record Library * * A library to interface with the NoSQL database MongoDB. For more information see http://www.mongodb.org * Originally created by Alex Bilbie, but extended and updated by Kyle J. Dye * * @package CodeIgniter * @author Alex Bilbie | www.alexbilbie.com | alex@alexbilbie.com * @author Kyle J. Dye | www.kyledye.com | kyle@kyledye.com * @copyright Copyright (c) 2010, Alex Bilbie. * @license http://codeigniter.com/user_guide/license.html * @link http://alexbilbie.com * @link http://kyledye.com * @version Version 0.3.7 */ class Mongo_db { private $CI; private $config_file = 'mongodb'; private $connection; private $db; private $connection_string; private $host; private $port; private $user; private $pass; private $dbname; private $persist; private $persist_key; private $query_safety = 'safe'; private $selects = array(); public $wheres = array(); // Public to make debugging easier private $sorts = array(); private $limit = 999999; private $offset = 0; /** * -------------------------------------------------------------------------------- * CONSTRUCTOR * -------------------------------------------------------------------------------- * * Automatically check if the Mongo PECL extension has been installed/enabled. * Generate the connection string and establish a connection to the MongoDB. */ public function __construct() { if ( ! class_exists('Mongo')) { show_error("The MongoDB PECL extension has not been installed or enabled", 500); } $this->CI =& get_instance(); $this->connection_string(); $this->connect(); } /** * -------------------------------------------------------------------------------- * Switch_db * -------------------------------------------------------------------------------- * * Switch from default database to a different db */ public function switch_db($database = '') { if (empty($database)) { show_error("To switch MongoDB databases, a new database name must be specified", 500); } $this->dbname = $database; try { $this->db = $this->connection->{$this->dbname}; return (TRUE); } catch (Exception $e) { show_error("Unable to switch Mongo Databases: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * Drop_db * -------------------------------------------------------------------------------- * * Drop a Mongo database * @usage: $this->mongo_db->drop_db("foobar"); */ public function drop_db($database = '') { if (empty($database)) { show_error('Failed to drop MongoDB database because name is empty', 500); } else { try { $this->connection->{$database}->drop(); return (TRUE); } catch (Exception $e) { show_error("Unable to drop Mongo database `{$database}`: {$e->getMessage()}", 500); } } } /** * -------------------------------------------------------------------------------- * Drop_collection * -------------------------------------------------------------------------------- * * Drop a Mongo collection * @usage: $this->mongo_db->drop_collection('foo', 'bar'); */ public function drop_collection($db = "", $col = "") { if (empty($db)) { show_error('Failed to drop MongoDB collection because database name is empty', 500); } if (empty($col)) { show_error('Failed to drop MongoDB collection because collection name is empty', 500); } else { try { $this->connection->{$db}->{$col}->drop(); return TRUE; } catch (Exception $e) { show_error("Unable to drop Mongo collection `{$col}`: {$e->getMessage()}", 500); } } return($this); } /** * -------------------------------------------------------------------------------- * SELECT FIELDS * -------------------------------------------------------------------------------- * * Determine which fields to include OR which to exclude during the query process. * Currently, including and excluding at the same time is not available, so the * $includes array will take precedence over the $excludes array. If you want to * only choose fields to exclude, leave $includes an empty array(). * * @usage: $this->mongo_db->select(array('foo', 'bar'))->get('foobar'); */ public function select($includes = array(), $excludes = array()) { if ( ! is_array($includes)) { $includes = array(); } if ( ! is_array($excludes)) { $excludes = array(); } if ( ! empty($includes)) { foreach ($includes as $col) { $this->selects[$col] = 1; } } else { foreach ($excludes as $col) { $this->selects[$col] = 0; } } return ($this); } /** * -------------------------------------------------------------------------------- * WHERE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents based on these search parameters. The $wheres array should * be an associative array with the field as the key and the value as the search * criteria. * * @usage : $this->mongo_db->where(array('foo' => 'bar'))->get('foobar'); */ public function where($wheres = array()) { foreach ($wheres as $wh => $val) { $this->wheres[$wh] = $val; } return ($this); } /** * -------------------------------------------------------------------------------- * OR_WHERE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field may be something else * * @usage : $this->mongo_db->or_where(array( array('foo'=>'bar', 'bar'=>'foo' ))->get('foobar'); */ public function or_where($wheres = array()) { if (count($wheres) > 0) { if ( ! isset($this->wheres['$or']) || ! is_array($this->wheres['$or'])) { $this->wheres['$or'] = array(); } foreach ($wheres as $wh => $val) { $this->wheres['$or'][] = array($wh=>$val); } } return ($this); } /** * -------------------------------------------------------------------------------- * WHERE_IN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is in a given $in array(). * * @usage : $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */ public function where_in($field = "", $in = array()) { $this->_where_init($field); $this->wheres[$field]['$in'] = $in; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE_IN_ALL PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is in all of a given $in array(). * * @usage : $this->mongo_db->where_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */ public function where_in_all($field = "", $in = array()) { $this->_where_init($field); $this->wheres[$field]['$all'] = $in; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE_NOT_IN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is not in a given $in array(). * * @usage : $this->mongo_db->where_not_in('foo', array('bar', 'zoo', 'blah'))->get('foobar'); */ public function where_not_in($field = "", $in = array()) { $this->_where_init($field); $this->wheres[$field]['$nin'] = $in; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE GREATER THAN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is greater than $x * * @usage : $this->mongo_db->where_gt('foo', 20); */ public function where_gt($field = "", $x) { $this->_where_init($field); $this->wheres[$field]['$gt'] = $x; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE GREATER THAN OR EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is greater than or equal to $x * * @usage : $this->mongo_db->where_gte('foo', 20); */ public function where_gte($field = "", $x) { $this->_where_init($field); $this->wheres[$field]['$gte'] = $x; return($this); } /** * -------------------------------------------------------------------------------- * WHERE LESS THAN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is less than $x * * @usage : $this->mongo_db->where_lt('foo', 20); */ public function where_lt($field = "", $x) { $this->_where_init($field); $this->wheres[$field]['$lt'] = $x; return($this); } /** * -------------------------------------------------------------------------------- * WHERE LESS THAN OR EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is less than or equal to $x * * @usage : $this->mongo_db->where_lte('foo', 20); */ public function where_lte($field = "", $x) { $this->_where_init($field); $this->wheres[$field]['$lte'] = $x; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE BETWEEN PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is between $x and $y * * @usage : $this->mongo_db->where_between('foo', 20, 30); */ public function where_between($field = "", $x, $y) { $this->_where_init($field); $this->wheres[$field]['$gte'] = $x; $this->wheres[$field]['$lte'] = $y; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE BETWEEN AND NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is between but not equal to $x and $y * * @usage : $this->mongo_db->where_between_ne('foo', 20, 30); */ public function where_between_ne($field = "", $x, $y) { $this->_where_init($field); $this->wheres[$field]['$gt'] = $x; $this->wheres[$field]['$lt'] = $y; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the value of a $field is not equal to $x * * @usage : $this->mongo_db->where_not_equal('foo', 1)->get('foobar'); */ public function where_ne($field = '', $x) { $this->_where_init($field); $this->wheres[$field]['$ne'] = $x; return ($this); } /** * -------------------------------------------------------------------------------- * WHERE NOT EQUAL TO PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents nearest to an array of coordinates (your collection must have a geospatial index) * * @usage : $this->mongo_db->where_near('foo', array('50','50'))->get('foobar'); */ function where_near($field = '', $co = array()) { $this->__where_init($field); $this->where[$what]['$near'] = $co; return ($this); } /** * -------------------------------------------------------------------------------- * LIKE PARAMETERS * -------------------------------------------------------------------------------- * * Get the documents where the (string) value of a $field is like a value. The defaults * allow for a case-insensitive search. * * @param $flags * Allows for the typical regular expression flags: * i = case insensitive * m = multiline * x = can contain comments * l = locale * s = dotall, "." matches everything, including newlines * u = match unicode * * @param $enable_start_wildcard * If set to anything other than TRUE, a starting line character "^" will be prepended * to the search value, representing only searching for a value at the start of * a new line. * * @param $enable_end_wildcard * If set to anything other than TRUE, an ending line character "$" will be appended * to the search value, representing only searching for a value at the end of * a line. * * @usage : $this->mongo_db->like('foo', 'bar', 'im', FALSE, TRUE); */ public function like($field = "", $value = "", $flags = "i", $enable_start_wildcard = TRUE, $enable_end_wildcard = TRUE) { $field = (string) trim($field); $this->where_init($field); $value = (string) trim($value); $value = quotemeta($value); if ($enable_start_wildcard !== TRUE) { $value = "^" . $value; } if ($enable_end_wildcard !== TRUE) { $value .= "$"; } $regex = "/$value/$flags"; $this->wheres[$field] = new MongoRegex($regex); return ($this); } /** * -------------------------------------------------------------------------------- * ORDER BY PARAMETERS * -------------------------------------------------------------------------------- * * Sort the documents based on the parameters passed. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage : $this->mongo_db->where_between('foo', 20, 30); */ public function order_by($fields = array()) { foreach ($fields as $col => $val) { if ($val == -1 || $val === FALSE || strtolower($val) == 'desc') { $this->sorts[$col] = -1; } else { $this->sorts[$col] = 1; } } return ($this); } /** * -------------------------------------------------------------------------------- * LIMIT DOCUMENTS * -------------------------------------------------------------------------------- * * Limit the result set to $x number of documents * * @usage : $this->mongo_db->limit($x); */ public function limit($x = 99999) { if ($x !== NULL && is_numeric($x) && $x >= 1) { $this->limit = (int) $x; } return ($this); } /** * -------------------------------------------------------------------------------- * OFFSET DOCUMENTS * -------------------------------------------------------------------------------- * * Offset the result set to skip $x number of documents * * @usage : $this->mongo_db->offset($x); */ public function offset($x = 0) { if ($x !== NULL && is_numeric($x) && $x >= 1) { $this->offset = (int) $x; } return ($this); } /** * -------------------------------------------------------------------------------- * GET_WHERE * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage : $this->mongo_db->get_where('foo', array('bar' => 'something')); */ public function get_where($collection = "", $where = array()) { return ($this->where($where)->get($collection)); } /** * -------------------------------------------------------------------------------- * GET * -------------------------------------------------------------------------------- * * Get the documents based upon the passed parameters * * @usage : $this->mongo_db->get('foo', array('bar' => 'something')); */ public function get($collection = "") { if (empty($collection)) { show_error("In order to retreive documents from MongoDB, a collection name must be passed", 500); } $results = array(); $documents = $this->db->{$collection}->find($this->wheres, $this->selects)->limit((int) $this->limit)->skip((int) $this->offset)->sort($this->sorts); // Clear $this->_clear(); $returns = array(); foreach ($documents as $doc) { $returns[] = $doc; } if ($this->CI->config->item('mongo_return') == 'object') { return (object)$returns; } else { return $returns; } } /** * -------------------------------------------------------------------------------- * COUNT * -------------------------------------------------------------------------------- * * Count the documents based upon the passed parameters * * @usage : $this->mongo_db->get('foo'); */ public function count($collection = "") { if (empty($collection)) { show_error("In order to retreive a count of documents from MongoDB, a collection name must be passed", 500); } $count = $this->db->{$collection}->find($this->wheres)->limit((int) $this->limit)->skip((int) $this->offset)->count(); $this->_clear(); return ($count); } /** * -------------------------------------------------------------------------------- * INSERT * -------------------------------------------------------------------------------- * * Insert a new document into the passed collection * * @usage : $this->mongo_db->insert('foo', $data = array()); */ public function insert($collection = "", $insert = array()) { if (empty($collection)) { show_error("No Mongo collection selected to insert into", 500); } if (count($insert) == 0 || !is_array($insert)) { show_error("Nothing to insert into Mongo collection or insert is not an array", 500); } try { $this->db->{$collection}->insert($insert, array( "w" => 1)); if (isset($insert['_id'])) { return ($insert['_id']); } else { return (FALSE); } } catch (MongoCursorException $e) { show_error("Insert of data into MongoDB failed: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * UPDATE * -------------------------------------------------------------------------------- * * Updates a single document * * @usage: $this->mongo_db->update('foo', $data = array()); */ public function update($collection = "", $data = array(), $options = array()) { if (empty($collection)) { show_error("No Mongo collection selected to update", 500); } if (count($data) == 0 || ! is_array($data)) { show_error("Nothing to update in Mongo collection or update is not an array", 500); } try { $options = array_merge($options, array("w" => 1, 'multiple' => FALSE)); $this->db->{$collection}->update($this->wheres, array('$set' => $data), $options); $this->_clear(); return (TRUE); } catch (MongoCursorException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * UPDATE_ALL * -------------------------------------------------------------------------------- * * Updates a collection of documents * * @usage: $this->mongo_db->update_all('foo', $data = array()); */ public function update_all($collection = "", $data = array()) { if (empty($collection)) { show_error("No Mongo collection selected to update", 500); } if (count($data) == 0 || ! is_array($data)) { show_error("Nothing to update in Mongo collection or update is not an array", 500); } try { $this->db->{$collection}->update($this->wheres, array('$set' => $data), array($this->query_safety => TRUE, 'multiple' => TRUE)); $this->_clear(); return (TRUE); } catch (MongoCursorException $e) { show_error("Update of data into MongoDB failed: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * DELETE * -------------------------------------------------------------------------------- * * delete document from the passed collection based upon certain criteria * * @usage : $this->mongo_db->delete('foo', $data = array()); */ public function delete($collection = "") { if (empty($collection)) { show_error("No Mongo collection selected to delete from", 500); } try { $this->db->{$collection}->remove($this->wheres, array($this->query_safety => TRUE, 'justOne' => TRUE)); $this->_clear(); return (TRUE); } catch (MongoCursorException $e) { show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * DELETE_ALL * -------------------------------------------------------------------------------- * * Delete all documents from the passed collection based upon certain criteria * * @usage : $this->mongo_db->delete_all('foo', $data = array()); */ public function delete_all($collection = "") { if (empty($collection)) { show_error("No Mongo collection selected to delete from", 500); } try { $this->db->{$collection}->remove($this->wheres, array($this->query_safety => TRUE, 'justOne' => FALSE)); $this->_clear(); return (TRUE); } catch (MongoCursorException $e) { show_error("Delete of data into MongoDB failed: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * COMMAND * -------------------------------------------------------------------------------- * * Runs a MongoDB command (such as GeoNear). See the MongoDB documentation for more usage scenarios: * http://dochub.mongodb.org/core/commands * * @usage : $this->mongo_db->command(array('geoNear'=>'buildings', 'near'=>array(53.228482, -0.547847), 'num' => 10, 'nearSphere'=>true)); */ public function command($query = array()) { try { $run = $this->db->command($query); return $run; } catch (MongoCursorException $e) { show_error("MongoDB command failed to execute: {$e->getMessage()}", 500); } } /** * -------------------------------------------------------------------------------- * ADD_INDEX * -------------------------------------------------------------------------------- * * Ensure an index of the keys in a collection with optional parameters. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage : $this->mongo_db->add_index($collection, array('first_name' => 'ASC', 'last_name' => -1), array('unique' => TRUE)); */ public function add_index($collection = "", $keys = array(), $options = array()) { if (empty($collection)) { show_error("No Mongo collection specified to add index to", 500); } if (empty($keys) || ! is_array($keys)) { show_error("Index could not be created to MongoDB Collection because no keys were specified", 500); } foreach ($keys as $col => $val) { if($val == -1 || $val === FALSE || strtolower($val) == 'desc') { $keys[$col] = -1; } else { $keys[$col] = 1; } } if ($this->db->{$collection}->ensureIndex($keys, $options) == TRUE) { $this->_clear(); return ($this); } else { show_error("An error occured when trying to add an index to MongoDB Collection", 500); } } /** * -------------------------------------------------------------------------------- * REMOVE_INDEX * -------------------------------------------------------------------------------- * * Remove an index of the keys in a collection. To set values to descending order, * you must pass values of either -1, FALSE, 'desc', or 'DESC', else they will be * set to 1 (ASC). * * @usage : $this->mongo_db->remove_index($collection, array('first_name' => 'ASC', 'last_name' => -1)); */ public function remove_index($collection = "", $keys = array()) { if (empty($collection)) { show_error("No Mongo collection specified to remove index from", 500); } if (empty($keys) || ! is_array($keys)) { show_error("Index could not be removed from MongoDB Collection because no keys were specified", 500); } if ($this->db->{$collection}->deleteIndex($keys, $options) == TRUE) { $this->_clear(); return ($this); } else { show_error("An error occured when trying to remove an index from MongoDB Collection", 500); } } /** * -------------------------------------------------------------------------------- * REMOVE_ALL_INDEXES * -------------------------------------------------------------------------------- * * Remove all indexes from a collection. * * @usage : $this->mongo_db->remove_all_index($collection); */ public function remove_all_indexes($collection = "") { if (empty($collection)) { show_error("No Mongo collection specified to remove all indexes from", 500); } $this->db->{$collection}->deleteIndexes(); $this->_clear(); return ($this); } /** * -------------------------------------------------------------------------------- * LIST_INDEXES * -------------------------------------------------------------------------------- * * Lists all indexes in a collection. * * @usage : $this->mongo_db->list_indexes($collection); */ public function list_indexes($collection = "") { if (empty($collection)) { show_error("No Mongo collection specified to remove all indexes from", 500); } return ($this->db->{$collection}->getIndexInfo()); } /** * -------------------------------------------------------------------------------- * CONNECT TO MONGODB * -------------------------------------------------------------------------------- * * Establish a connection to MongoDB using the connection string generated in * the connection_string() method. If 'mongo_persist_key' was set to true in the * config file, establish a persistent connection. We allow for only the 'persist' * option to be set because we want to establish a connection immediately. */ private function connect() { $options = array(); if ($this->persist === TRUE) { $options['persist'] = isset($this->persist_key) && !empty($this->persist_key) ? $this->persist_key : 'ci_mongo_persist'; } try { $this->connection = new MongoClient($this->connection_string, $options); $this->db = $this->connection->{$this->dbname}; return ($this); } catch (MongoConnectionException $e) { if($this->CI->config->item('mongo_supress_connect_error')) { show_error("Unable to connect to MongoDB", 500); } else { show_error("Unable to connect to MongoDB: {$e->getMessage()}", 500); } } } /** * -------------------------------------------------------------------------------- * BUILD CONNECTION STRING * -------------------------------------------------------------------------------- * * Build the connection string from the config file. */ private function connection_string() { $this->CI->config->load($this->config_file); $this->host = trim($this->CI->config->item('mongo_host')); $this->port = trim($this->CI->config->item('mongo_port')); $this->user = trim($this->CI->config->item('mongo_user')); $this->pass = trim($this->CI->config->item('mongo_pass')); $this->dbname = trim($this->CI->config->item('mongo_db')); $this->persist = trim($this->CI->config->item('mongo_persist')); $this->persist_key = trim($this->CI->config->item('mongo_persist_key')); $this->query_safety = trim($this->CI->config->item('mongo_query_safety')); $dbhostflag = (bool)$this->CI->config->item('host_db_flag'); $connection_string = "mongodb://"; if (empty($this->host)) { show_error("The Host must be set to connect to MongoDB", 500); } if (empty($this->dbname)) { show_error("The Database must be set to connect to MongoDB", 500); } if ( ! empty($this->user) && ! empty($this->pass)) { $connection_string .= "{$this->user}:{$this->pass}@"; } if (isset($this->port) && ! empty($this->port)) { $connection_string .= "{$this->host}:{$this->port}"; } else { $connection_string .= "{$this->host}"; } if ($dbhostflag === TRUE) { $this->connection_string = trim($connection_string) . '/' . $this->dbname; } else { $this->connection_string = trim($connection_string); } } /** * -------------------------------------------------------------------------------- * _clear * -------------------------------------------------------------------------------- * * Resets the class variables to default settings */ private function _clear() { $this->selects = array(); $this->wheres = array(); $this->limit = 999999; $this->offset = 0; $this->sorts = array(); } /** * -------------------------------------------------------------------------------- * WHERE INITIALIZER * -------------------------------------------------------------------------------- * * Prepares parameters for insertion in $wheres array(). */ private function _where_init($param) { if ( ! isset($this->wheres[$param])) { $this->wheres[ $param ] = array(); } } } // EOF
使用redis也需要安装redis扩展
redis.php放config目录
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Config for the CodeIgniter Redis library * * @see ../libraries/Redis.php */ // Default connection group $config['redis_default']['host'] = '127.0.0.1‘; $config['redis_default']['port'] = '6379'; // Default Redis port is 6379 $config['redis_default']['password'] = ''; // Can be left empty when the server does not require AUTH $config['redis_slave']['host'] = ''; $config['redis_slave']['port'] = '6379'; $config['redis_slave']['password'] = '';
Redis.php放library目录
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * CodeIgniter Redis * * A CodeIgniter library to interact with Redis * * @package CodeIgniter * @category Libraries * @author Joël Cox * @version v0.4 * @link https://github.com/joelcox/codeigniter-redis * @link http://joelcox.nl * @license http://www.opensource.org/licenses/mit-license.html */ class CI_Redis { /** * CI * * CodeIgniter instance * @var object */ private $_ci; /** * Connection * * Socket handle to the Redis server * @var handle */ private $_connection; /** * Debug * * Whether we're in debug mode * @var bool */ public $debug = TRUE; /** * CRLF * * User to delimiter arguments in the Redis unified request protocol * @var string */ const CRLF = " "; /** * Constructor */ public function __construct($params = array()) { log_message('debug', 'Redis Class Initialized'); $this->_ci = get_instance(); $this->_ci->load->config('redis'); // Check for the different styles of configs if (isset($params['connection_group'])) { // Specific connection group $config = $this->_ci->config->item('redis_' . $params['connection_group']); } elseif (is_array($this->_ci->config->item('redis_default'))) { // Default connection group $config = $this->_ci->config->item('redis_default'); } else { // Original config style $config = array( 'host' => $this->_ci->config->item('redis_host'), 'port' => $this->_ci->config->item('redis_port'), 'password' => $this->_ci->config->item('redis_password'), ); } // Connect to Redis $this->_connection = @fsockopen($config['host'], $config['port'], $errno, $errstr, 3); // Display an error message if connection failed if ( ! $this->_connection) { show_error('Could not connect to Redis at ' . $config['host'] . ':' . $config['port']); } // Authenticate when needed $this->_auth($config['password']); } /** * Call * * Catches all undefined methods * @param string method that was called * @param mixed arguments that were passed * @return mixed */ public function __call($method, $arguments) { $request = $this->_encode_request($method, $arguments); return $this->_write_request($request); } /** * Command * * Generic command function, just like redis-cli * @param string full command as a string * @return mixed */ public function command($string) { $slices = explode(' ', $string); $request = $this->_encode_request($slices[0], array_slice($slices, 1)); return $this->_write_request($request); } /** * Auth * * Runs the AUTH command when password is set * @param string password for the Redis server * @return void */ private function _auth($password = NULL) { // Authenticate when password is set if ( ! empty($password)) { // See if we authenticated successfully if ($this->command('AUTH ' . $password) !== 'OK') { show_error('Could not connect to Redis, invalid password'); } } } /** * Clear Socket * * Empty the socket buffer of theconnection so data does not bleed over * to the next message. * @return NULL */ public function _clear_socket() { // Read one character at a time fflush($this->_connection); return NULL; } /** * Write request * * Write the formatted request to the socket * @param string request to be written * @return mixed */ private function _write_request($request) { if ($this->debug === TRUE) { //log_message('debug', 'Redis unified request: ' . $request); } // How long is the data we are sending? $value_length = strlen($request); // If there isn't any data, just return if ($value_length <= 0) return NULL; // Handle reply if data is less than or equal to 8192 bytes, just send it over if ($value_length <= 8192) { fwrite($this->_connection, $request); } else { while ($value_length > 0) { // If we have more than 8192, only take what we can handle if ($value_length > 8192) { $send_size = 8192; } // Send our chunk fwrite($this->_connection, $request, $send_size); // How much is left to send? $value_length = $value_length - $send_size; // Remove data sent from outgoing data $request = substr($request, $send_size, $value_length); } } // Read our request into a variable $return = $this->_read_request(); // Clear the socket so no data remains in the buffer $this->_clear_socket(); return $return; } /** * Read request * * Route each response to the appropriate interpreter * @return mixed */ private function _read_request() { $type = fgetc($this->_connection); // Times we will attempt to trash bad data in search of a // valid type indicator $response_types = array('+', '-', ':', '$', '*'); $type_error_limit = 50; $try = 0; while ( ! in_array($type, $response_types) && $try < $type_error_limit) { $type = fgetc($this->_connection); $try++; } if ($this->debug === TRUE) { log_message('debug', 'Redis response type: ' . $type); } switch ($type) { case '+': return $this->_single_line_reply(); break; case '-': return $this->_error_reply(); break; case ':': return $this->_integer_reply(); break; case '$': return $this->_bulk_reply(); break; case '*': return $this->_multi_bulk_reply(); break; default: return FALSE; } } /** * Single line reply * * Reads the reply before the EOF * @return mixed */ private function _single_line_reply() { $value = rtrim(fgets($this->_connection)); $this->_clear_socket(); return $value; } /** * Error reply * * Write error to log and return false * @return bool */ private function _error_reply() { // Extract the error message $error = substr(rtrim(fgets($this->_connection)), 4); log_message('error', 'Redis server returned an error: ' . $error); $this->_clear_socket(); return FALSE; } /** * Integer reply * * Returns an integer reply * @return int */ private function _integer_reply() { return (int) rtrim(fgets($this->_connection)); } /** * Bulk reply * * Reads to amount of bits to be read and returns value within * the pointer and the ending delimiter * @return string */ private function _bulk_reply() { // How long is the data we are reading? Support waiting for data to // fully return from redis and enter into socket. $value_length = (int) fgets($this->_connection); if ($this->debug === TRUE) { log_message('debug', 'Redis response length: ' . $value_length); } if ($value_length <= 0) return NULL; $response = ''; // Handle reply if data is less than or equal to 8192 bytes, just read it if ($value_length <= 8192) { //$response = fread($this->_connection, $value_length); //fix read_size error // Read our chunk $read_size = $value_length; $chunk = fread($this->_connection, $read_size); // Support reading very long responses that don't come through // in one fread $chunk_length = strlen($chunk); while ($chunk_length < $read_size) { $keep_reading = $read_size - $chunk_length; $chunk .= fread($this->_connection, $keep_reading); $chunk_length = strlen($chunk); } $response = $chunk; } else { $data_left = $value_length; // If the data left is greater than 0, keep reading while ($data_left > 0 ) { // If we have more than 8192, only take what we can handle if ($data_left > 8192) { $read_size = 8192; } else { $read_size = $data_left; } // Read our chunk $chunk = fread($this->_connection, $read_size); // Support reading very long responses that don't come through // in one fread $chunk_length = strlen($chunk); while ($chunk_length < $read_size) { $keep_reading = $read_size - $chunk_length; $chunk .= fread($this->_connection, $keep_reading); $chunk_length = strlen($chunk); } $response .= $chunk; // Re-calculate how much data is left to read $data_left = $data_left - $read_size; } } if ($this->debug === TRUE) { log_message('debug', 'Redis response real_length is: ' . strlen($response)); if ($value_length != strlen($response)) { log_message('debug', 'Redis response get a output-error'); } } // Clear the socket in case anything remains in there $this->_clear_socket(); return isset($response) ? $response : FALSE; } /** * Multi bulk reply * * Reads n bulk replies and return them as an array * @return array */ private function _multi_bulk_reply() { // Get the amount of values in the response $response = array(); $total_values = (int) fgets($this->_connection); // Loop all values and add them to the response array for ($i = 0; $i < $total_values; $i++) { // Remove the new line and carriage return before reading // another bulk reply fgets($this->_connection, 2); // If this is a second or later pass, we also need to get rid // of the $ indicating a new bulk reply and its length. if ($i > 0) { fgets($this->_connection); fgets($this->_connection, 2); } $response[] = $this->_bulk_reply(); } // Clear the socket $this->_clear_socket(); return isset($response) ? $response : FALSE; } /** * Encode request * * Encode plain-text request to Redis protocol format * @link http://redis.io/topics/protocol * @param string request in plain-text * @param string additional data (string or array, depending on the request) * @return string encoded according to Redis protocol */ private function _encode_request($method, $arguments = array()) { $request = '$' . strlen($method) . self::CRLF . $method . self::CRLF; $_args = 1; // Append all the arguments in the request string foreach ($arguments as $argument) { if (is_array($argument)) { foreach ($argument as $key => $value) { // Prepend the key if we're dealing with a hash if (!is_int($key)) { $request .= '$' . strlen($key) . self::CRLF . $key . self::CRLF; $_args++; } $request .= '$' . strlen($value) . self::CRLF . $value . self::CRLF; $_args++; } } else { $request .= '$' . strlen($argument) . self::CRLF . $argument . self::CRLF; $_args++; } } $request = '*' . $_args . self::CRLF . $request; return $request; } /** * Info * * Overrides the default Redis response, so we can return a nice array * of the server info instead of a nasty string. * @return array */ public function info($section = FALSE) { if ($section !== FALSE) { $response = $this->command('INFO '. $section); } else { $response = $this->command('INFO'); } $data = array(); $lines = explode(self::CRLF, $response); // Extract the key and value foreach ($lines as $line) { $parts = explode(':', $line); if (isset($parts[1])) $data[$parts[0]] = $parts[1]; } return $data; } /** * Debug * * Set debug mode * @param bool set the debug mode on or off * @return void */ public function debug($bool) { $this->debug = (bool) $bool; } /** * Destructor * * Kill the connection * @return void */ function __destruct() { log_message('debug', 'Redis Class destruct'); if ($this->_connection) fclose($this->_connection); } }