tp5 redis 单例模式 转载

单例模式(Singleton Pattern 单件模式或单元素模式)

单例模式确保某个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

单例模式有以下3个特点:

1 . 它必须有一个构造函数,而且构造函数必须为私有

2.必须有一个保存实例的静态成员变量

3.拥有一个访问这个实例的公共的静态方法

为什么使用单例模式?

PHP一个主要应用场合就是应用程序与数据库打交道的场景,在一个应用中会存在大量的数据库操作,针对数据库句柄连接数据库的行为,使用单例模式可以避免大量的new操作。因为每一次new操作都会消耗系统和内存的资源。

单例模式下面上代码:

复制代码
<?php
/**
 * Created by PhpStorm.
 * User: luxiao
 * Date: 2017/4/19
 * Time: 16:21
 */

namespace My;

class RedisPackage
{
    private static $handler = null;
    private static $_instance = null;
    private static $options = [
        'host' => '127.0.0.1',
        'port' => 6379,
        'password' => '',
        'select' => 0,
        'timeout' => 0,
        'expire' => 0,
        'persistent' => false,
        'prefix' => '',
    ];

    private function __construct($options = [])
    {
        if (!extension_loaded('redis')) {
            throw new BadFunctionCallException('not support: redis');      //判断是否有扩展
        }
        if (!empty($options)) {
            self::$options = array_merge(self::$options, $options);
        }
        $func = self::$options['persistent'] ? 'pconnect' : 'connect';     //长链接
        self::$handler = new Redis;
        self::$handler->$func(self::$options['host'], self::$options['port'], self::$options['timeout']);

        if ('' != self::$options['password']) {
            self::$handler->auth(self::$options['password']);
        }

        if (0 != self::$options['select']) {
            self::$handler->select(self::$options['select']);
        }
    }


    /**
     * @return RedisPackage|null 对象
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 禁止外部克隆
     */
    public function __clone()
    {
        trigger_error('Clone is not allow!',E_USER_ERROR);
    }

    /**
     * 写入缓存
     * @param string $key 键名
     * @param string $value 键值
     * @param int $exprie 过期时间 0:永不过期
     * @return bool
     */


    public static function set($key, $value, $exprie = 0)
    {
        if ($exprie == 0) {
            $set = self::$handler->set($key, $value);
        } else {
            $set = self::$handler->setex($key, $exprie, $value);
        }
        return $set;
    }

    /**
     * 读取缓存
     * @param string $key 键值
     * @return mixed
     */
    public static function get($key)
    {
        $fun = is_array($key) ? 'Mget' : 'get';
        return self::$handler->{$fun}($key);
    }

    /**
     * 获取值长度
     * @param string $key
     * @return int
     */
    public static function lLen($key)
    {
        return self::$handler->lLen($key);
    }

    /**
     * 将一个或多个值插入到列表头部
     * @param $key
     * @param $value
     * @return int
     */
    public static function LPush($key, $value)
    {
        return self::$handler->lPush($key, $value);
    }

    /**
     * 移出并获取列表的第一个元素
     * @param string $key
     * @return string
     */
    public static function lPop($key)
    {
        return self::$handler->lPop($key);
    }
}
复制代码

基类控制器Base.php

复制代码
<?php
/**
 * Created by PhpStorm.
 * User: luxiao
 * Date: 2017/4/20
 * Time: 14:39
 */

namespace appindexcontroller;
use thinkController;
use MyRedisPackage;

class Base extends Controller
{
    protected static $redis;

    public function __construct()
    {
        parent::__construct();
            self::$redis=RedisPackage::getInstance();
    }
}
复制代码

Redis控制器 Redis.php

复制代码
<?php
/**
 * Created by PhpStorm.
 * User: luxiao
 * Date: 2017/4/19
 * Time: 14:39
 */

namespace appindexcontroller;

use appindexcontrollerBase;

class Redis extends Base
{
    function redis()
    {
        self::$redis->set('zai','肖哥');
        echo self::$redis->get('zai');
    }
}
原文地址:https://www.cnblogs.com/liliuguang/p/9388782.html