Cache_Memcache.class.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. /**
  3. * Cache strategy using Memcache extension
  4. *
  5. * @author Christopher Han <xiphux@gmail.com>
  6. * @copyright Copyright (c) 2012 Christopher Han
  7. * @package GitPHP
  8. * @subpackage Cache
  9. */
  10. class GitPHP_Cache_Memcache implements GitPHP_CacheStrategy_Interface
  11. {
  12. /**
  13. * Memcache object
  14. *
  15. * @var Memcached
  16. */
  17. protected $memcache;
  18. /**
  19. * Constructor
  20. *
  21. * @param array[] $servers server array
  22. */
  23. public function __construct($servers)
  24. {
  25. if (!class_exists('Memcache'))
  26. throw new Exception('Memcache extension not found');
  27. if ((!$servers) || (!is_array($servers)) || (count($servers) < 1)) {
  28. throw new GitPHP_MessageException('No Memcache servers defined', true, 500);
  29. }
  30. $this->memcache = new Memcache();
  31. foreach ($servers as $server) {
  32. if (is_array($server)) {
  33. $host = $server[0];
  34. $port = 11211;
  35. if (isset($server[1]))
  36. $port = $server[1];
  37. $weight = 1;
  38. if (isset($server[2]))
  39. $weight = $server[2];
  40. $this->memcache->addServer($host, $port, true, $weight);
  41. }
  42. }
  43. }
  44. /**
  45. * Gets an item from the cache
  46. *
  47. * @param string $key cache key
  48. * @return mixed cached object or false if not found
  49. */
  50. public function Get($key)
  51. {
  52. if (empty($key))
  53. return false;
  54. return $this->memcache->get($key);
  55. }
  56. /**
  57. * Sets an item into the cache
  58. *
  59. * @param string $key cache key
  60. * @param mixed $value object to cache
  61. * @param int $lifetime cached object lifetime
  62. */
  63. public function Set($key, $value, $lifetime)
  64. {
  65. if (empty($key) || empty($value))
  66. return;
  67. $this->memcache->set($key, $value, false, time() + $lifetime);
  68. }
  69. /**
  70. * Check if an item exists
  71. *
  72. * @param string $key cache key
  73. * @return boolean true if exists
  74. */
  75. public function Exists($key)
  76. {
  77. return ($this->Get($key) !== false);
  78. }
  79. /**
  80. * Delete an item from the cache
  81. *
  82. * @param string $key cache key
  83. */
  84. public function Delete($key)
  85. {
  86. if (empty($key))
  87. return;
  88. $this->memcache->delete($key);
  89. }
  90. /**
  91. * Clear the cache
  92. */
  93. public function Clear()
  94. {
  95. $this->memcache->flush();
  96. }
  97. }