WechatCache.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. use Psr\SimpleCache\CacheInterface;
  5. /**
  6. * Class WechatCache
  7. * @package common\components
  8. * @author jianyan74 <751393839@qq.com>
  9. */
  10. class WechatCache implements CacheInterface
  11. {
  12. /**
  13. * @var int
  14. */
  15. protected $setTime = 0;
  16. /**
  17. * @param string $key
  18. * @param null $default
  19. * @return mixed|null
  20. */
  21. public function get($key, $default = null)
  22. {
  23. if ($data = Yii::$app->cache->get($key)) {
  24. return $data;
  25. }
  26. return $default;
  27. }
  28. /**
  29. * @param string $key
  30. * @param mixed $value
  31. * @param null $ttl
  32. * @return bool
  33. */
  34. public function set($key, $value, $ttl = null)
  35. {
  36. $this->setTime = time();
  37. return Yii::$app->cache->set($key, $value, $ttl);
  38. }
  39. /**
  40. * @param string $key
  41. * @return bool
  42. */
  43. public function delete($key)
  44. {
  45. return Yii::$app->cache->delete($key);
  46. }
  47. /**
  48. * @return bool
  49. */
  50. public function clear()
  51. {
  52. return Yii::$app->cache->flush();
  53. }
  54. /**
  55. * @param array $keys
  56. * @param null $default
  57. * @return array|iterable
  58. */
  59. public function getMultiple($keys, $default = null)
  60. {
  61. return Yii::$app->cache->multiGet($keys) ?? $default;
  62. }
  63. /**
  64. * @param array $values
  65. * @param null $ttl
  66. * @return array|bool
  67. */
  68. public function setMultiple($values, $ttl = null)
  69. {
  70. $this->setTime = time();
  71. return Yii::$app->cache->multiSet($values, $ttl);
  72. }
  73. /**
  74. * @param array $keys
  75. * @return bool|void
  76. */
  77. public function deleteMultiple($keys)
  78. {
  79. foreach ($keys as $key) {
  80. $this->delete($key);
  81. }
  82. }
  83. /**
  84. * @param string $key
  85. * @return bool
  86. */
  87. public function has($key)
  88. {
  89. if ($this->setTime > 0) {
  90. return true;
  91. }
  92. if (($data = Yii::$app->cache->get($key)) && !empty($data)) {
  93. return true;
  94. }
  95. return false;
  96. }
  97. }
粤ICP备19079148号