<?php
/**
* 可以存取字符串,数组,对象的Redis自定义类
* Class MyRedis
*/
class MyRedis{
private static $handler;
private static function handler(){
if(!self::$handler){
self::$handler = new Redis();
self::$handler -> connect('127.0.0.1','6379');
}
return self::$handler;
}
public static function get($key){
$value = self::handler() -> get($key);
$value_serl = @unserialize($value);
if(is_object($value_serl)||is_array($value_serl)){
return $value_serl;
}
return $value;
}
public static function set($key,$value){
if(is_object($value)||is_array($value)){
$value = serialize($value);
}
return self::handler() -> set($key,$value);
}
public static function del($key){
return self::handler() -> del($key);
}
}
测试demo:
<?php
require_once 'MyRedis.php';
class MyObj{
public function rTime(){
return time();
}
}
$arr = ['name'=>'starsea','info'=>['sex'=>'男','age'=>23]];
$obj = new MyObj();
$str = 'Redis 测试';
MyRedis::set('arr',$arr);
MyRedis::set('obj',$obj);
MyRedis::set('str',$str);
//
$_arr = MyRedis::get('arr');
$_obj = MyRedis::get('obj');
$_str = MyRedis::get('str');
MyRedis::del('arr');
var_dump($_arr);
var_dump($_obj->rTime());
var_dump($_str);