Cache_Memcached.class.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /**
  3. * Cache strategy using Memcached 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_Memcached implements GitPHP_CacheStrategy_Interface
  11. {
  12. /**
  13. * Memcached 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('Memcached'))
  26. throw new Exception('Memcached 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 Memcached();
  31. $this->memcache->addServers($servers);
  32. }
  33. /**
  34. * Gets an item from the cache
  35. *
  36. * @param string $key cache key
  37. * @return mixed cached object or false if not found
  38. */
  39. public function Get($key)
  40. {
  41. if (empty($key))
  42. return false;
  43. return $this->memcache->get($key);
  44. }
  45. /**
  46. * Sets an item into the cache
  47. *
  48. * @param string $key cache key
  49. * @param mixed $value object to cache
  50. * @param int $lifetime cached object lifetime
  51. */
  52. public function Set($key, $value, $lifetime)
  53. {
  54. if (empty($key) || empty($value))
  55. return;
  56. $this->memcache->set($key, $value, time() + $lifetime);
  57. }
  58. /**
  59. * Check if an item exists
  60. *
  61. * @param string $key cache key
  62. * @return boolean true if exists
  63. */
  64. public function Exists($key)
  65. {
  66. return ($this->Get($key) !== false);
  67. }
  68. /**
  69. * Delete an item from the cache
  70. *
  71. * @param string $key cache key
  72. */
  73. public function Delete($key)
  74. {
  75. if (empty($key))
  76. return;
  77. $this->memcache->delete($key);
  78. }
  79. /**
  80. * Clear the cache
  81. */
  82. public function Clear()
  83. {
  84. $this->memcache->flush();
  85. }
  86. }