CacheServices.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. * @mixin CacheDao
  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 string|callable|int|array $default 默认值不存在则写入
  29. * @param int $expire
  30. * @return mixed|null
  31. */
  32. public function getDbCache(string $key, $default, int $expire = 0)
  33. {
  34. $this->dao->delectDeOverdueDbCache();
  35. $result = $this->dao->value(['key' => $key], 'result');
  36. if ($result) {
  37. return json_decode($result, true);
  38. } else {
  39. if ($default instanceof \Closure) {
  40. // 获取缓存数据
  41. $value = $default();
  42. if ($value) {
  43. $this->setDbCache($key, $value, $expire);
  44. return $value;
  45. }
  46. } else {
  47. $this->setDbCache($key, $default, $expire);
  48. return $default;
  49. }
  50. return null;
  51. }
  52. }
  53. /**
  54. * 设置数据缓存存在则更新,没有则写入
  55. * @param string $key
  56. * @param $result
  57. * @param $expire
  58. * @return \crmeb\basic\BaseModel|mixed|\think\Model
  59. * @throws \Exception
  60. */
  61. public function setDbCache(string $key, $result, $expire = 0)
  62. {
  63. $this->dao->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. */
  84. public function delectDbCache(string $key = '')
  85. {
  86. if ($key)
  87. return $this->dao->delete($key, 'key');
  88. else
  89. return false;
  90. }
  91. }