CacheServices.php 2.9 KB

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