Maison  >  Article  >  développement back-end  >  php写的一个缓存接口demo,兼容redis和memcache

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

WBOY
WBOYoriginal
2016-07-25 09:03:541057parcourir
  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. ?>
复制代码


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn