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

WBOY
发布: 2016-07-25 09:03:54
原创
1114 人浏览过
  1. /**

  2. * 工厂方法模式
  3. * -------------
  4. * @author zhangqian
  5. * @version v1.0
  6. */
  7. //缓存接口
  8. interface cache {
  9. public function init($conf);
  10. public function setVal($key , $val);
  11. public function getVal($key);
  12. public function delVal($key);
  13. public function autoIncreament($key);
  14. }
  15. //mem
  16. class mymemCache implements cache {
  17. //mymem连接
  18. public function init($conf)
  19. {
  20. echo '初始化mymem';
  21. }
  22. public function setVal($key , $val)
  23. {
  24. echo 'mem设置值';
  25. }
  26. public function getVal($key)
  27. {
  28. echo 'mem获取值';
  29. }
  30. public function delVal($key)
  31. {
  32. echo 'mem删除值';
  33. }
  34. public function autoIncreament($key)
  35. {
  36. echo 'mem自增';
  37. }
  38. }
  39. //redis
  40. class redisCache implements cache {
  41. //redis连接
  42. public function init($arr)
  43. {
  44. echo '初始化redis';
  45. }
  46. public function setVal($key , $val)
  47. {
  48. echo 'redis设置值';
  49. }
  50. public function getVal($key)
  51. {
  52. echo 'redis获取值';
  53. }
  54. public function delVal($key)
  55. {
  56. echo 'redis删除值';
  57. }
  58. public function autoIncreament($key)
  59. {
  60. echo 'redis自增';
  61. }
  62. }
  63. class cacheFactory
  64. {
  65. private static $obj;
  66. private static $type;
  67. private static $conf;
  68. private static $allowtype = array('mymem','redis');
  69. private static function getConfig()
  70. {
  71. //include_once('config.php');加载配置文件 获取缓存的类型 及缓存的配置参数
  72. global $_SC;
  73. self::$type = $_SC['cachetype'];//做空值的判断
  74. self::$conf = $_SC['cacheconf'];//做空值的判断
  75. }
  76. //外部调用创建缓存对象
  77. public static function CreateOperation(){
  78. self::getConfig();
  79. try
  80. {
  81. $error = '未知的缓存类型';
  82. if(in_array(self::$type , self::$allowtype))
  83. {
  84. $type = self::$type.'Cache';
  85. self::$obj = new $type;
  86. self::$obj->init(self::$conf);//连接
  87. }
  88. else
  89. throw new Exception($error);
  90. }
  91. catch (Exception $e) {
  92. echo 'Caught exception: ', $e->getMessage(), "\n";
  93. exit;
  94. }
  95. return self::$obj;
  96. }
  97. }
  98. $_SC = array();

  99. $_SC['cachetype'] = 'redis';//mymem
  100. $_SC['cacheconf'] = array();
  101. $cache = cacheFactory::CreateOperation();
  102. $cache->setVal('a',1);
  103. echo '
    ';
  104. $a = $cache->getVal('a');
  105. echo '
    ';
  106. $cache->delVal('a');
  107. ?>
复制代码


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板