您的位置:首页 > 数据库 > Redis

redis 类

2015-12-03 12:10 288 查看
公司需要刚封装的redis类,简单,好用

<?php

/**
* redis 封装类
* User: gaojisheng
* Date: 15/12/3
* Time: 上午9:28
*/
class My_Redis {

//redis内部对象
protected $_instance;

/**
* @param string|null $name 服务器名
*/
public function __construct(string $name = null) {
if($name == null) {
$config = $this->_getConfig($name);
}
$this->_connect($config);
}

public function __call($func, array $params) {
return call_user_func_array(array($this->_instance, $func), $params);
}

/**
* 连接redis
* @param array $config 配置
*/
protected function _connect(array $config) {
$this->_instance = new Redis();

$this->_instance->connect($config['host'], $config['port']);
if (isset($config['password']) && $config['password'] != null) {
$this->_instance->auth($config['password']);
}
$this->select($config['db']);
}

/**
* 选择库
* @param $db 库
*/
public function select($db) {
$this->_instance->select($db);
}

/**
* 获取配置文件
* @param string|null $name 服务器名
* @return array 配置信息
*/
protected function _getConfig(string $name = null) {
$configs = yaml_parse_file(__DIR__.'/redis.yaml');
if($name == null) {
foreach($configs as $key => $item) {
$name = $key;
}
}

if(isset($configs[$name])) {
return array_merge($configs[$name], array('title' => $name));
}

return array();
}
}

/**
* 对外提供的方法
* @param string|null $name 服务器名
* @return My_Redis redis对象
*/
function create(string $name = null) {
return new My_Redis();
}

/**
* 单例对外提供的方法
* @param string|null $name 服务器名
* @return My_Redis redis对象
*/
function instance(string $name = null) {
static $instances = array();
if(empty($instances[$name])) {
return $instances[$name] = create($name);
}

return $instances[$name];
}


使用方法

print_r(create()->get("test"));
print_r(instance()->get("test"));


配置文件使用的是yaml

---
rite:
host: 127.0.0.1
port: 6379
db: 1
password: ""
rite2:
host: 127.0.0.1
port: 6379
db: 1
password: gaojstest
...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis 对象 yaml