ArrayCache.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\caching;
  8. /**
  9. * ArrayCache provides caching for the current request only by storing the values in an array.
  10. *
  11. * See [[Cache]] for common cache operations that ArrayCache supports.
  12. *
  13. * Unlike the [[Cache]], ArrayCache allows the expire parameter of [[set]], [[add]], [[multiSet]] and [[multiAdd]] to
  14. * be a floating point number, so you may specify the time in milliseconds (e.g. 0.1 will be 100 milliseconds).
  15. *
  16. * For enhanced performance of ArrayCache, you can disable serialization of the stored data by setting [[$serializer]] to `false`.
  17. *
  18. * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
  19. *
  20. * @author Carsten Brandt <mail@cebe.cc>
  21. * @since 2.0
  22. */
  23. class ArrayCache extends Cache
  24. {
  25. private $_cache = [];
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function exists($key)
  30. {
  31. $key = $this->buildKey($key);
  32. return isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true));
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. protected function getValue($key)
  38. {
  39. if (isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true))) {
  40. return $this->_cache[$key][0];
  41. }
  42. return false;
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. protected function setValue($key, $value, $duration)
  48. {
  49. $this->_cache[$key] = [$value, $duration === 0 ? 0 : microtime(true) + $duration];
  50. return true;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. protected function addValue($key, $value, $duration)
  56. {
  57. if (isset($this->_cache[$key]) && ($this->_cache[$key][1] === 0 || $this->_cache[$key][1] > microtime(true))) {
  58. return false;
  59. }
  60. $this->_cache[$key] = [$value, $duration === 0 ? 0 : microtime(true) + $duration];
  61. return true;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. protected function deleteValue($key)
  67. {
  68. unset($this->_cache[$key]);
  69. return true;
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. protected function flushValues()
  75. {
  76. $this->_cache = [];
  77. return true;
  78. }
  79. }