MemcacheCache.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace Doctrine\Common\Cache;
  3. use Memcache;
  4. use function time;
  5. /**
  6. * Memcache cache provider.
  7. *
  8. * @deprecated
  9. *
  10. * @link www.doctrine-project.org
  11. */
  12. class MemcacheCache extends CacheProvider
  13. {
  14. /** @var Memcache|null */
  15. private $memcache;
  16. /**
  17. * Sets the memcache instance to use.
  18. *
  19. * @return void
  20. */
  21. public function setMemcache(Memcache $memcache)
  22. {
  23. $this->memcache = $memcache;
  24. }
  25. /**
  26. * Gets the memcache instance used by the cache.
  27. *
  28. * @return Memcache|null
  29. */
  30. public function getMemcache()
  31. {
  32. return $this->memcache;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. protected function doFetch($id)
  38. {
  39. return $this->memcache->get($id);
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected function doContains($id)
  45. {
  46. $flags = null;
  47. $this->memcache->get($id, $flags);
  48. //if memcache has changed the value of "flags", it means the value exists
  49. return $flags !== null;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. protected function doSave($id, $data, $lifeTime = 0)
  55. {
  56. if ($lifeTime > 30 * 24 * 3600) {
  57. $lifeTime = time() + $lifeTime;
  58. }
  59. return $this->memcache->set($id, $data, 0, (int) $lifeTime);
  60. }
  61. /**
  62. * {@inheritdoc}
  63. */
  64. protected function doDelete($id)
  65. {
  66. // Memcache::delete() returns false if entry does not exist
  67. return $this->memcache->delete($id) || ! $this->doContains($id);
  68. }
  69. /**
  70. * {@inheritdoc}
  71. */
  72. protected function doFlush()
  73. {
  74. return $this->memcache->flush();
  75. }
  76. /**
  77. * {@inheritdoc}
  78. */
  79. protected function doGetStats()
  80. {
  81. $stats = $this->memcache->getStats();
  82. return [
  83. Cache::STATS_HITS => $stats['get_hits'],
  84. Cache::STATS_MISSES => $stats['get_misses'],
  85. Cache::STATS_UPTIME => $stats['uptime'],
  86. Cache::STATS_MEMORY_USAGE => $stats['bytes'],
  87. Cache::STATS_MEMORY_AVAILABLE => $stats['limit_maxbytes'],
  88. ];
  89. }
  90. }