淺談php封裝redis操作類

<?php
namespace core;

/**
* 緩存類
*/
class Cache
{
	private $redis;
	private $index = 0;

	function __construct($index='')
	{
		//實例化Redis類
		$redis = new \Redis();
		$redis->connect('127.0.0.1', 6379);
		$this->redis = $redis;
		if($index){
			$this->index = $index;
		}
		$redis->select($this->index);
	}

	public function setCache($key,$value,$expire=7200){
		$redis = $this->redis;
		$set = $redis->set($key,$value);
		$redis->expire($key,$expire);
		return $set;
	}

	public function getCache($key){
		$redis = $this->redis;
		$val = $redis->get($key);
		return $val;
	}

	public function onlySetCache($key,$value){
		$redis = $this->redis;
		$set = $redis->set($key,$value);
		return $set;
	}

	public function getExpire($key){
		$redis = $this->redis;
		$time = $redis->ttl($key);
		return $time;
	}

	public function deleteCache($key){
		$redis = $this->redis;
		$res = $redis->delete($key);
		return $res;
	}

	//redis 哈希處理方法

	/**
	* 把數據儲存入hash表中,若表不存在自動創建表 以及對應的key並賦值
	* 如果key已經存在 則會覆蓋舊值
	*
	* @param string key 鍵
	* @param string field 字段
	* @param mix value 值
	*
	* @return boolen
	**/
	public function hset($key, $field, $value){
		$redis = $this->redis;
		$res = $redis->hSet($key, $field, $value);
		return $res;
	}

	/**
	* 根據 key-field獲取hash表數據
	*
	* @param string key 鍵
	* @param string field 字段
	*
	* @return mixed
	**/
	public function hget($key, $field){
		$redis = $this->redis;
		$res = $redis->hGet($key, $field);
		return $res;
	}

	/**
	* 獲取hash表的字段數量
	*
	* @param string key 鍵
	*
	* @return mixed
	**/
	public function hlen($key){
		$redis = $this->redis;
		$len = $redis->hLen($key);
		return $len;
	}

	/**
	* 根據 key-field獲取hash表所有數據
	*
	* @param string key 鍵
	*
	* @return mixed
	**/
	public function hgetAll($key){
		$redis = $this->redis;
		$res = $redis->hGetAll($key);
		return $res;
	}

	/**
     * 刪除hash表中的某個字段
     * @param string $key    表名
     * @param string $field  字段名
     * @return bool
	 */
	public function hdel($key,$field)
	{
		$redis = $this->redis;
		$redis->hdel($key,$field);
		if($redis){
			return true;
		}else{
			return false;
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章