您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CacheServices.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace app\services\other;
  3. use app\dao\other\CacheDao;
  4. use app\services\BaseServices;
  5. /**
  6. * Class CacheServices
  7. * @package app\services\other
  8. * @method delectDeOverdueDbCache() 删除过期缓存
  9. */
  10. class CacheServices extends BaseServices
  11. {
  12. public function __construct(CacheDao $dao)
  13. {
  14. $this->dao = $dao;
  15. }
  16. /**
  17. * 获取数据缓存
  18. * @param string $key
  19. * @param string|callable|int|array $default 默认值不存在则写入
  20. * @param int $expire
  21. * @return mixed|null
  22. */
  23. public function getDbCache(string $key, $default, int $expire = 0)
  24. {
  25. $this->delectDeOverdueDbCache();
  26. $result = $this->dao->value(['key' => $key], 'result');
  27. if ($result) {
  28. return json_decode($result, true);
  29. } else {
  30. if ($default instanceof \Closure) {
  31. // 获取缓存数据
  32. $value = $default();
  33. if ($value) {
  34. $this->setDbCache($key, $value, $expire);
  35. return $value;
  36. }
  37. } else {
  38. $this->setDbCache($key, $default, $expire);
  39. return $default;
  40. }
  41. return null;
  42. }
  43. }
  44. /**
  45. * 设置数据缓存存在则更新,没有则写入
  46. * @param string $key
  47. * @param string | array $result
  48. * @param int $expire
  49. * @return void
  50. */
  51. public function setDbCache(string $key, $result, $expire = 0)
  52. {
  53. $this->delectDeOverdueDbCache();
  54. $addTime = $expire ? time() + $expire : 0;
  55. if ($this->dao->count(['key' => $key])) {
  56. return $this->dao->update($key, [
  57. 'result' => json_encode($result),
  58. 'expire_time' => $addTime,
  59. 'add_time' => time()
  60. ], 'key');
  61. } else {
  62. return $this->dao->save([
  63. 'key' => $key,
  64. 'result' => json_encode($result),
  65. 'expire_time' => $addTime,
  66. 'add_time' => time()
  67. ]);
  68. }
  69. }
  70. /**
  71. * 删除某个缓存
  72. * @param string $key
  73. */
  74. public function delectDbCache(string $key = '')
  75. {
  76. if ($key)
  77. return $this->dao->delete($key, 'key');
  78. else
  79. return false;
  80. }
  81. }