php写的一个缓存接口demo,兼容redis和memcache

发布时间:2019-11-30编辑:脚本学堂
一个缓存接口demo,可以兼容redis和memcache,redis的高级特性没有添加进去,大家可以自行添加。

一个缓存接口demo,可以兼容redis和memcache,redis的高级特性没有添加进去,大家可以自行添加。
 

复制代码 代码如下:

<?php
    /**
     * 工厂方法模式
     * -------------
     * @author      zhangqian
     * @version     v1.0
     */
    //缓存接口
    interface cache {
        public function init($conf);
        public function setVal($key , $val);
        public function getVal($key);
        public function delVal($key);
        public function autoIncreament($key);
    }
    //mem
    class mymemCache implements cache {
        //mymem连接
        public function init($conf)
        {
            echo '初始化mymem';
        }
        public function setVal($key , $val)
        {
            echo 'mem设置值';
        }
        public function getVal($key)
        {
            echo 'mem获取值';
        }
        public function delVal($key)
        {
            echo 'mem删除值';
        }
        public function autoIncreament($key)
        {
            echo 'mem自增';
        }
    }
    //redis
    class redisCache  implements cache {
        //redis连接
        public function init($arr)
        {
            echo '初始化redis';
        }
        public function setVal($key , $val)
        {
            echo 'redis设置值';
        }
        public function getVal($key)
        {
            echo 'redis获取值';
        }
        public function delVal($key)
        {
            echo 'redis删除值';
        }
        public function autoIncreament($key)
        {
            echo 'redis自增';
        }
    }
    class cacheFactory
    {
        private static $obj;
        private static $type;
        private static $conf;
        private static $allowtype = array('mymem','redis');
        private static function getConfig()
        {
            //include_once('config.php');加载配置文件 获取缓存的类型 及缓存的配置参数
            global $_SC;
            self::$type = $_SC['cachetype'];//做空值的判断
            self::$conf = $_SC['cacheconf'];//做空值的判断
        }
        //外部调用创建缓存对象
        public static function CreateOperation(){
            self::getConfig();
            try
            {
                $error = '未知的缓存类型';
                if(in_array(self::$type , self::$allowtype))
                {
                    $type = self::$type.'Cache';
                    self::$obj = new $type;
                    self::$obj->init(self::$conf);//连接
                }
                else
                    throw new Exception($error);
            }
            catch (Exception $e) {
                echo 'Caught exception: ',  $e->getMessage(), "n";
                exit;
            }
            return self::$obj;
        }
    }

    $_SC = array();
    $_SC['cachetype'] = 'redis';//mymem
    $_SC['cacheconf'] = array();
  
    $cache = cacheFactory::CreateOperation();
    $cache->setVal('a',1);
    echo '<br />';
    $a = $cache->getVal('a');
    echo '<br />';
    $cache->delVal('a');
  ?>