PHP redis class

<?php

namespace Home\Model;
class Redis
{
    /** @var \Predis\Client|\Redis */
    protected $handler;
    /**
     * 配置参数
     * @var array
     */
    protected $options = [
        'host'       => '127.0.0.1',
        'port'       => 6379,
        'password'   => '',
        'select'     => 0,
        'timeout'    => 0,
        'expire'     => 0,
        'persistent' => false,
        'prefix'     => '',
        'tag_prefix' => 'tag:',
        'serialize'  => [],
    ];     * @access public     * Architecture functions
    /**

     * @param array $options 缓存参数
     */
    public function __construct(array $options = [])
    {
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        if (extension_loaded('redis')) {
            $this->handler = new \Redis;
            if ($this->options['persistent']) {
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
            } else {
                $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
            }
            if ('' != $this->options['password']) {
                $this->handler->auth($this->options['password']);
            }
        } elseif (class_exists('\Predis\Client')) {
            $params = [];
            foreach ($this->options as $key => $val) {
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
                    $params[$key] = $val;
                    unset($this->options[$key]);
                }
            }
            if ('' == $this->options['password']) {
                unset($this->options['password']);
            }
            $this->handler = new \Predis\Client($this->options, $params);
            $this->options['prefix'] = '';
        } else {
            throw new \BadFunctionCallException('not support: redis');
        }
        if (0 != $this->options['select']) {
            $this->handler->select((int) $this->options['select']);
        }
    }
    /**
     * 设置一个key
     * @param unknown $key
     * @param unknown $value
     */
    public function set($key,$value)
    {
        return $this->handler->set($key,$value);     */     * @param unknown $key     * get a key    /**
    }


    public function get($key) 
    { 
        return $this->handler->get($key); 
    } 
    /** 
     * set a key with expiration time 
     * @param unknown $key 
     * @param unknown $expire 
     * @param unknown $value 
     */ 
    public function setex($key,$expire,$value) 
    { 
        return $this->handler->setex($key,$expire,$value); 
    } 

    /** 
     * Set a key, if the key exists , do nothing. 
     * @param unknown $key 
     * @param unknown $value 
     */ 
    public function setnx($key,$value) 
    { 
        return $this->handler->setnx($key,$value); 
    } 
    / ** 
     * Set keys in batches
     * @param unknown $arr 
     */ 
    public function mset($arr) 
    { 
        return $this->handler->mset($arr); 
    } 
    /** 
     * Add one to the numeric value stored in key 
     * @param [type ] $key [description] 
     * @return [type] [description] 
     */ 
    public function setincr($key) 
    { 
        return $this->handler->incr($key); 
    } 
    /********* ********hash table operation function ********************/ 
    /** 
     * Get the value of a field in the hash table 
     * @param string $key cache key 
     * @param string $field field 
     * @return string|false 
     */ 
    public function hGet($key,$field) 
    {
        return $this->handler->hGet($key,$field); 
    } 
    /** 
     * Set a field value for the hash table 
     * @param string $key cache key 
     * @param string $field field 
     * @param string $value value. 
     * @return bool 
     */ 
    public function hSet($key,$field,$value) 
    { 
        return $this->handler->hSet($key,$field,$value); 
    } 
    /** 
     * Judge the hash table, Specify whether the field exists 
     * @param string $key cache key 
     * @param string $field field 
     * @return bool 
     */ 
    public function hExists($key,$field) 
    { 
        return $this->handler->hExists($key, $field); 
    } 
    /**
     * Delete the specified field in the hash table, support batch deletion 
     * @param string $key cache key 
     * @param string $field field 
     * @return int 
     */ 
    public function hdel($key, $field) 
    { 
        $fieldArr=explode(', ',$field); 
        $delNum=0; 
        foreach($fieldArr as $row) 
        { 
            $row=trim($row); 
            $delNum+=$this->handler->hDel($key,$row); 
        } 
        return $delNum; 
    } 
    /** 
     * Return the number of hash table elements 
     * @param string $key cache key 
     * @return int|bool 
     */ 
    public function hLen($key) 
    { 
        return $this->handler->hLen($key );
    } 
    /** 
     * Set the value of a field for the hash table, if the field exists, return false 
     * @param string $key cache key 
     * @param string $field field 
     * @param string $value value. 
     * @return bool 
     */ 
    public function hSetNx($key,$field,$value) 
    { 
        return $this->handler->hSetNx($key,$field,$value); 
    } 
    /** 
     * multiple hash tables Field setting value. 
     * @param string $key 
     * @param array $value 
     * @return array|bool 
     */ 
    public function hMset($key,$value) 
    { 
        if(!is_array($value)) 
            return false; 
        return $this->handler- >hMset($key,$value); 
    }
    /** 
     * Set values ​​for multiple fields in the hash table. 
     * @param string $key 
     * @param array|string $value string Separate fields with ',' 
     * @return array|bool 
     */ 
    public function hMget($key,$field) 
    { 
        if(!is_array($field)) 
            $field=explode(',', $field); 
        return $this->handler->hMget($key,$field); 
    } 
    /** 
     * Set this accumulation for the hash table, it can be negative 
     * @param string $key 
     * @param int $field 
     * @param string $value 
     * @return bool 
     */ 
    public function hIncrBy($key,$field,$value) 
    { 
        $value=intval($value);
        return $this->handler->hIncrBy($key,$field,$value); 
    } 
    /** 
     * Return all fields of all hash tables 
     * @param string $key 
     * @return array|bool 
     */ 
    public function hKeys( $key) 
    { 
        return $this->handler->hKeys($key); 
    } 
    /** 
     * Returns all hash table field values ​​as an index array 
     * @param string $key 
     * @return array|bool 
     */ 
    public function hVals($key) 
    { 
        return $this->handler->hVals($key); 
    } 
    /** 
     * Returns all hash table field values ​​as an associative array 
     * @param string $key 
     * @return array|bool 
     */
    public function hGetAll($key) 
    { 
        return $this->handler->hGetAll($key); 
    } 
    /************************Ordered set operation* ********************/ 
    /** 
     * Add an element to the current collection 
     * If value already exists, the value of order will be updated. 
     * @param string $key 
     * @param string $order number 
     * @param string $value value 
     * @return bool 
     */ 
    public function zAdd($key,$order,$value) 
    { 
        return $this->handler->zAdd( $key,$order,$value); 
    } 
    /** 
     * Add $num to the order value of the $value member, which can be negative 
     * @param string $key 
     * @param string $num serial number 
     * @param string $value value
     * @return return new order 
     */ 
    public function zinCry($key,$num,$value) 
    { 
        return $this->handler->zinCry($key,$num,$value); 
    } 
    /** 
     * delete value The element of value 
     * @param string $key 
     * @param stirng $value 
     * @return bool 
     */ 
    public function zRem($key,$value) 
    { 
        return $this->handler->zRem($key,$value); 
    } 
    /** 
     * After the collection is arranged in increasing order, 0 means the first element, -1 means the last element 
     * @param string $key 
     * @param int $start 
     * @param int $end 
     * @return array|bool 
     * / 
    public function zRange($key,$start,$end)
    { 
        return $this->handler->zRange($key,$start,$end); 
    } 
    /** 
     * After the collection is arranged in descending order, 0 means the first element, -1 means the last element 
     * @param string $key 
     * @param int $start 
     * @param int $end 
     * @return array|bool 
     */ 
    public function zRevRange($key,$start,$end) 
    { 
        return $this->handler->zRevRange($key,$ start,$end); 
    } 
    /** 
     * After the collection is arranged in increasing order, return the elements between the specified order. 
     * min and max can be -inf and +inf for maximum value, minimum value 
     * @param string $key 
     * @param int $start 
     * @param int $end 
     * @package array $option parameter 
     * withscores=>true, which means array The subscript is the Order value, and the default returns the index array
     * limit=>array(0,1) means starting from 0 and taking a record. 
     * @return array|bool 
     */ 
    public function zRangeByScore($key,$start='-inf',$end="+inf",$option=array()) 
    { 
        return $this->handler->zRangeByScore($ key,$start,$end,$option); 
    } 
    /** 
     * After the collection is arranged in descending order, return the elements between the specified order. 
     * min and max can be -inf and +inf for maximum value, minimum value 
     * @param string $key 
     * @param int $start 
     * @param int $end 
     * @package array $option parameter 
     * withscores=>true, which means array The subscript is the Order value, and the default return index array 
     * limit=>array(0,1) means starting from 0 and fetching a record. 
     * @return array|bool 
     */
    public function zRevRangeByScore($key,$start='-inf',$end="+inf",$option=array()) 
    { 
        return $this->handler->zRevRangeByScore($key,$start,$end, $option); 
    } 
    /** 
     * Returns the number of order values ​​between start and end 
     * @param unknown $key 
     * @param unknown $start 
     * @param unknown $end 
     */ 
    public function zCount($key,$start,$ end) 
    { 
        return $this->handler->zCount($key,$start,$end); 
    } 
    /** 
     * The return value is the order value of value 
     * @param unknown $key 
     * @param unknown $value 
     */ 
    public function zScore($key,$value) 
    {
        return $this->handler->zScore($key,$value); 
    } 
    /** 
     * After the returned set is sorted by increasing score, the sorting number of the specified member starts from 0. 
     * @param unknown $key 
     * @param unknown $value 
     */ 
    public function zRank($key,$value) 
    { 
        return $this->handler->zRank($key,$value); 
    } 
    /** 
     * Returns the set as After the score is incremented and sorted, specify the sorting number of the member, starting from 0. 
     * @param unknown $key 
     * @param unknown $value 
     */ 
    public function zRevRank($key,$value) 
    { 
        return $this->handler->zRevRank($key,$value); 
    } 
    /** 
     * delete from the set , the elements whose score value is between start end include start end 
     * min and max can be -inf and +inf represent the maximum value, the minimum value
     * @param unknown $key 
     * @param unknown $start 
     * @param unknown $end 
     * @return Number of deleted members. 
     */ 
    public function zRemRangeByScore($key,$start,$end) 
    { 
        return $this->handler->zRemRangeByScore($key,$start,$end); 
    } 
    /** 
     * Returns the number of set elements. 
     * @param unknown $key 
     */ 
    public function zCard($key) 
    { 
        return $this->handler->zCard($key); 
    } 

    /****************** ***Queue operation command ************************/ 
    /** 
     * Insert an element at the end of the queue 
     * @param unknown $key 
     * @param unknown $value 
     * return queue length 
     */
    public function rPush($key,$value) 
    { 
        return $this->handler->rPush($key,$value); 
    } 
    /** 
     * Insert an element at the end of the queue If key does not exist, do nothing 
     * @ param unknown $key 
     * @param unknown $value 
     * return queue length 
     */ 
    public function rPushx($key,$value) 
    { 
        return $this->handler->rPushx($key,$value); 
    } 
    /** 
     * in Insert an element at the head of the queue 
     * @param unknown $key 
     * @param unknown $value 
     * Return the length of the queue 
     */ 
    public function lPush($key,$value) 
    { 
        return $this->handler->lPush($key,$value ); 
    } 
    /**
     * Insert an element at the head of the queue If the key does not exist, do nothing 
     * @param unknown $key 
     * @param unknown $value 
     * Return the length of the queue 
     */ 
    public function lPushx($key,$value) 
    { 
        return $this-> handler->lPushx($key,$value); 
    } 
    /** 
     * return queue length 
     * @param unknown $key 
     */ 
    public function lLen($key) 
    { 
        return $this->handler->lLen($key); 
    } 
    /** 
     * Return the element of the specified range of the queue 
     * @param unknown $key 
     * @param unknown $start 
     * @param unknown $end 
     */ 
    public function lRange($key,$start,$end) 
    {
        return $this->handler->lrange($key,$start,$end); 
    } 
    /** 
     * Returns the element at the specified index in the queue 
     * @param unknown $key 
     * @param unknown $index 
     */ 
    public function lIndex( $key,$index) 
    { 
        return $this->handler->lIndex($key,$index); 
    } 
    /** 
     * Set the value of the specified index in the queue. 
     * @param unknown $key 
     * @param unknown $index 
     * @param unknown $value 
     */ 
    public function lSet($key,$index,$value) 
    { 
        return $this->handler->lSet($key,$index, $value); 
    } 
    /** 
     * delete count elements whose value is vaule
     * The data order of the PHP-REDIS extension is not the same as the order of the commands, I don't know if it's a bug 
     * count>0 starts from the tail 
     * >0 starts from the head 
     * =0 delete all 
     * @param unknown $key 
     * @param unknown $count 
     * @param unknown $value 
     */ 
    public function lRem($key,$count,$value) 
    { 
        return $this->handler->lRem($key,$value,$count); 
    } 
    /** 
     * delete and returns the head element in the queue. 
     * @param unknown $key 
     */ 
    public function lPop($key) 
    { 
        return $this->handler->lPop($key); 
    } 
    /** 
     * delete and return the tail element in the queue 
     * @param unknown $key 
     * / 
    public function rPop($key)
    { 
        return $this->handler->rPop($key); 
    } 

    /************redis unordered set operation command************** ***/ 
    /** 
     * Returns all elements in the collection 
     * @param unknown $key 
     */ 
    public function sMembers($key) 
    { 
        return $this->handler->sMembers($key); 
    } 
    /** 
     * Find 2 Difference of sets 
     * @param unknown $key1 
     * @param unknown $key2 
     */ 
    public function sDiff($key1,$key2) 
    { 
        return $this->handler->sDiff($key1,$key2); 
    } 
    /* * 
     * Add collection. Due to version issues, extensions do not support batch addition. Encapsulated here 
     * @param unknown $key 
     * @param string|array $value
     */ 
    public function sAdd($key,$value) 
    { 
        if(!is_array($value)) 
            $arr=array($value); 
        else 
            $arr=$value; 
        foreach($arr as $row) 
            $this-> handler->sAdd($key,$row); 
    } 
    /** 
     * Returns the number of elements in the unordered set 
     * @param unknown $key 
     */ 
    public function scard($key) 
    { 
        return $this->handler->scard ($key); 
    } 
    /** 
     * remove an element from the collection 
     * @param unknown $key 
     * @param unknown $value 
     */ 
    public function srem($key,$value) 
    {
        return $this->handler->srem($key,$value); 
    } 
    /************redis management operation command************** ***/ 
    /** 
     * Select database 
     * @param int $dbId database ID number 
     * @return bool 
     */ 
    public function select($dbId) 
    { 
        $this->dbId=$dbId; 
        return $this->handler-> select($dbId); 
    } 
    /** 
     * Flush the current database 
     * @return bool 
     */ 
    public function flushDB() 
    { 
        return $this->handler->flushDB(); 
    } 
    /** 
     * Return the current database status 
     * @return array 
     */ 
    public function info() 
    {
        return $this->handler->info(); 
    } 
    /** 
     * save data to disk synchronously 
     */ 
    public function save() 
    { 
        return $this->handler->save(); 
    } 
    /** 
     * save data asynchronously to disk 
     */ 
    public function bgSave() 
    { 
        return $this->handler->bgSave(); 
    } 
    /** 
     * Return the last time saved to disk 
     */ 
    public function lastSave() 
    { 
        return $this->handler-> lastSave(); 
    } 
    /** 
     * Return key, support * multiple characters, ? one character 
     * only * means all 
     * @param string $key 
     * @return array 
     */
    public function keys($key) 
    { 
        return $this->handler->keys($key); 
    } 
    /** 
     * delete the specified key 
     * @param unknown $key 
     */ 
    public function del($key) 
    { 
        return $this- >handler->del($key); 
    } 
    /** 
     * Determine if a key value exists 
     * @param unknown $key 
     */ 
    public function exists($key) 
    { 
        return $this->handler->exists($key ); 
    } 

    /** 
     * Set the expiration time for a key in seconds 
     * @param unknown $key 
     * @param unknown $expire 
     */ 
    public function expire($key,$expire) 
    {
        return $this->handler->expire($key,$expire); 
    } 
    /** 
     * Return how long a key will expire, in seconds 
     * @param unknown $key 
     */ 
    public function ttl($key) 
    { 
        return $ this->handler->ttl($key); 
    } 
    /** 
     * Set when a key expires, time is a timestamp 
     * @param unknown $key 
     * @param unknown $time 
     */ 
    public function exprieAt($key ,$time) 
    { 
        return $this->handler->expireAt($key,$time); 
    } 
    /** 
     * Close the server connection 
     */ 
    public function close() 
    { 
        return $this->handler->close(); 
    }
    /** 
     * Close all connections 
     */ 
    public static function closeAll() 
    { 
        foreach(static::$_instance as $o) 
        { 
            if($o instanceof self) 
                $o->close(); 
        } 
    } 
    /** not here Close the connection because session writes will be done after all objects are destroyed. 
    public function __destruct() 
    { 
        return $this->handler->close(); 
    } 
    **/ 
    /** 
     * Return the current number of database keys 
     */ 
    public function dbSize() 
    { 
        return $this->handler->dbSize() ; 
    } 
    /** 
     * Returns a random key 
     */ 
    public function randomKey()
    { 
        return $this->handler->randomKey(); 
    } 
    /** 
     * Get the current database ID 
     * @return int 
     */ 
    public function getDbId() 
    { 
        return $this->dbId; 
    } 
    /** 
     * Return the current password 
     * / 
    public function getAuth() 
    { 
        return $this->auth; 
    } 
    public function getHost() 
    { 
        return $this->host; 
    } 
    public function getPort() 
    { 
        return $this->port; 
    } 
    public function getConnInfo() 
    { 
        return array(
            'host'=>$this->host, 
            'port'=>$this->port, 
            'auth'=>$this->auth 
        ); 
    } 
    /************** ******Transaction related methods ************************/ 
    /** 
     * Monitoring key, that is, adding one or more keys An optimistic lock 
     * During this period, if the value of the key changes, just cannot set the value for the key 
     * The value of the key can be retrieved. 
     * @param unknown $key 
     */ 
    public function watch($key) 
    { 
        return $this->handler->watch($key); 
    } 
    /** 
     * Cancel the watch currently linked to all keys 
     * EXEC command or DISCARD command first If it is executed, then there is no need to execute UNWATCH again 
     */ 
    public function unwatch() 
    { 
        return $this->handler->
    } 
    /** 
     * Open a transaction 
     * There are two modes of transaction call Redis::MULTI and Redis::PIPELINE, 
     * The default is Redis::MULTI mode, 
     * Redis::PIPELINE pipeline mode is faster, but there is no guarantee Atomicity may cause data loss 
     */ 
    public function multi($type=\Redis::MULTI) 
    { 
        return $this->handler->multi($type); 
    } 
    /** 
     * Execute a transaction 
     * Receive EXEC After the command enters transaction execution, any command in the transaction fails to execute, and the rest of the commands are still executed 
     */ 
    public function exec() 
    { 
        return $this->handler->exec(); 
    } 
    /** 
     * Roll back a transaction 
     */ 
    public function discard() 
    { 
        return $this->handler->discard(); 
    }
    /** 
     * Test whether the current link has failed 
     * If there is no failure, return +PONG 
     * If it fails, return false 
     */ 
    public function ping() 
    { 
        return $this->handler->ping(); 
    } 
    public function auth($auth) 
    { 
        return $this->handler->auth($auth); 
    } 
    /********************Custom method to simplify operation**** ********************/ 
    /** 
     * Get a set of ID numbers 
     * @param unknown $prefix 
     * @param unknown $ids 
     */ 
    public function hashAll($ prefix,$ids) 
    { 
        if($ids==false) 
            return false; 
        if(is_string($ids)) 
            $ids=explode(',', $ids);
        $arr=array(); 
        foreach($ids as $id) 
        { 
            $key=$prefix.'.'.$id; 
            $res=$this->hGetAll($key); 
            if($res!=false) 
                $arr[]=$res; 
        } 
        return $arr; 
    } 
    /** 
     * Generate a message and put it in the redis database. Use library 0. 
     * @param string|array $msg 
     */ 
    public function pushMessage($lkey,$msg) 
    { 
        if(is_array($msg)){ 
            $msg = json_encode($msg); 
        } 
        $key = md5($msg); 
        / /If the message already exists, delete the old message, and the current message shall prevail.//echo 
        $n=$this->lRem($lkey, 0, $key)."\n"; 
        //Reset the new message
        $this->lPush($lkey, $key); 
        $this->setex($key, 3600, $msg); 
        return $key; 
    } 

    /** 
     * Get a command to delete keys in batches 
     * @param unknown $keys 
     * @param unknown $dbId 
     */ 
    public function delKeys($keys,$dbId) 
    { 
        $redisInfo=$this->getConnInfo(); 
        $cmdArr=array( 
            'redis-cli', 
            '-a', 
            $redisInfo[' auth'], 
            '-h', 
            $redisInfo['host'], 
            '-p', 
            $redisInfo['port'], 
            '-n', 
            $dbId, 
        );
        $redisStr=implode(' ', $cmdArr);
        $cmd="{$redisStr} KEYS \"{$keys}\" | xargs {$redisStr} del";
        return $cmd;
    }

}

Leave a Reply

Your email address will not be published.

en_USEnglish