redis 类

2 篇文章 0 订阅
1 篇文章 0 订阅

公司需要刚封装的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
...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值