CacheServices.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\other;
  12. use app\dao\other\CacheDao;
  13. use app\services\BaseServices;
  14. /**
  15. * 数据库表缓存
  16. * Class CacheServices
  17. * @package app\services\other
  18. * @method delectDeOverdueDbCache() 删除过期缓存
  19. */
  20. class CacheServices extends BaseServices
  21. {
  22. public function __construct(CacheDao $dao)
  23. {
  24. $this->dao = $dao;
  25. }
  26. /**
  27. * 获取数据缓存
  28. * @param string $key
  29. * @param $default 默认值不存在则写入
  30. * @param int $expire
  31. * @return mixed|null
  32. */
  33. public function getDbCache(string $key, $default, int $expire = 0)
  34. {
  35. $this->delectDeOverdueDbCache();
  36. $result = $this->dao->value(['key' => $key], 'result');
  37. if ($result) {
  38. return json_decode($result, true);
  39. } else {
  40. if ($default instanceof \Closure) {
  41. // 获取缓存数据
  42. $value = $default();
  43. if ($value) {
  44. $this->setDbCache($key, $value, $expire);
  45. return $value;
  46. }
  47. } else {
  48. $this->setDbCache($key, $default, $expire);
  49. return $default;
  50. }
  51. return null;
  52. }
  53. }
  54. /**
  55. * 设置数据缓存存在则更新,没有则写入
  56. * @param string $key
  57. * @param string | array $result
  58. * @param int $expire
  59. * @return void
  60. */
  61. public function setDbCache(string $key, $result, $expire = 0)
  62. {
  63. $this->delectDeOverdueDbCache();
  64. $addTime = $expire ? time() + $expire : 0;
  65. if ($this->dao->count(['key' => $key])) {
  66. return $this->dao->update($key, [
  67. 'result' => json_encode($result),
  68. 'expire_time' => $addTime,
  69. 'add_time' => time()
  70. ], 'key');
  71. } else {
  72. return $this->dao->save([
  73. 'key' => $key,
  74. 'result' => json_encode($result),
  75. 'expire_time' => $addTime,
  76. 'add_time' => time()
  77. ]);
  78. }
  79. }
  80. /**
  81. * 删除某个缓存
  82. * @param string $key
  83. * @return false|mixed
  84. */
  85. public function delectDbCache(string $key = '')
  86. {
  87. if ($key)
  88. return $this->dao->delete($key, 'key');
  89. else
  90. return false;
  91. }
  92. }