Home  >  Article  >  Backend Development  >  PHP connects redis database simple class_PHP tutorial

PHP connects redis database simple class_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:11:31951browse

PHP connection redis database single benefit class

<?php

class RedisConnect
{
    /**
     * Redis的ip
     *
     * @var string
     */
    const REDISHOSTNAME = "127.0.0.1";
    
    /**
     * Redis的port
     *
     * @var int
     */
    const REDISPORT = 6379;
    
    /**
     * Redis的超时时间
     *
     * @var int
     */
    const REDISTIMEOUT = 0;
    
    /**
     * Redis的password
     *
     * @var unknown_type
     */
    const REDISPASSWORD = "ehualu";
    
    /**
     * Redis的DBname
     *
     * @var int
     */
    const REDISDBNAME = 12;
    
    /**
     * 类单例
     *
     * @var object
     */
    private static $instance;
    
    /**
     * Redis的连接句柄
     *
     * @var object
     */
    private $redis;
    
    /**
     * 私有化构造函数,防止类外实例化
     *
     * @param unknown_type $dbnumber
     */
    private function __construct ()
    {
        // 链接数据库
        $this->redis = new Redis();
        $this->redis->connect(self::REDISHOSTNAME, self::REDISPORT, self::REDISTIMEOUT);
        $this->redis->auth(self::REDISPASSWORD);
        $this->redis->select(self::REDISDBNAME);
    }
    
    /**
     * 私有化克隆函数,防止类外克隆对象
     */
    private function __clone ()
    {}
    
    /**
     * 类的唯一公开静态方法,获取类单例的唯一入口
     *
     * @return object
     */
    public static function getRedisInstance ()
    {
        if (! (self::$instance instanceof self)) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 获取redis的连接实例
     *
     * @return Redis
     */
    public function getRedisConn ()
    {
        return $this->redis;
    }
    
    /**
     * 需要在单例切换的时候做清理工作
     */
    public function __destruct ()
    {
        self::$instance->redis->close();
        self::$instance = NULL;
    }
}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/929776.htmlTechArticlephp connect redis database simple class redis = new Redis(); $this->redis->connect(self ::REDISHOSTNAME, self::REDISPORT, self::REDISTIMEOUT); $this->redis->auth(self::REDISPASSWORD); $t...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn