PredisCache.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace Doctrine\Common\Cache;
  3. use Predis\Client;
  4. /**
  5. * Predis cache provider.
  6. *
  7. * @author othillo <othillo@othillo.nl>
  8. */
  9. class PredisCache extends CacheProvider
  10. {
  11. /**
  12. * @var Client
  13. */
  14. private $client;
  15. /**
  16. * @param Client $client
  17. *
  18. * @return void
  19. */
  20. public function __construct(Client $client)
  21. {
  22. $this->client = $client;
  23. }
  24. /**
  25. * {@inheritdoc}
  26. */
  27. protected function doFetch($id)
  28. {
  29. $result = $this->client->get($id);
  30. if (null === $result) {
  31. return false;
  32. }
  33. return unserialize($result);
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. protected function doFetchMultiple(array $keys)
  39. {
  40. $fetchedItems = call_user_func_array(array($this->client, 'mget'), $keys);
  41. return array_map('unserialize', array_filter(array_combine($keys, $fetchedItems)));
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. protected function doContains($id)
  47. {
  48. return $this->client->exists($id);
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. protected function doSave($id, $data, $lifeTime = 0)
  54. {
  55. $data = serialize($data);
  56. if ($lifeTime > 0) {
  57. $response = $this->client->setex($id, $lifeTime, $data);
  58. } else {
  59. $response = $this->client->set($id, $data);
  60. }
  61. return $response === true || $response == 'OK';
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. protected function doDelete($id)
  67. {
  68. return $this->client->del($id) >= 0;
  69. }
  70. /**
  71. * {@inheritdoc}
  72. */
  73. protected function doFlush()
  74. {
  75. $response = $this->client->flushdb();
  76. return $response === true || $response == 'OK';
  77. }
  78. /**
  79. * {@inheritdoc}
  80. */
  81. protected function doGetStats()
  82. {
  83. $info = $this->client->info();
  84. return array(
  85. Cache::STATS_HITS => $info['Stats']['keyspace_hits'],
  86. Cache::STATS_MISSES => $info['Stats']['keyspace_misses'],
  87. Cache::STATS_UPTIME => $info['Server']['uptime_in_seconds'],
  88. Cache::STATS_MEMORY_USAGE => $info['Memory']['used_memory'],
  89. Cache::STATS_MEMORY_AVAILABLE => false
  90. );
  91. }
  92. }