Cache.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace app\models\system;
  3. use crmeb\traits\ModelTrait;
  4. use crmeb\basic\BaseModel;
  5. /**
  6. * 数据缓存
  7. * Class Express
  8. * @package app\models\system
  9. */
  10. class Cache extends BaseModel
  11. {
  12. use ModelTrait;
  13. const EXPIRE = 0;
  14. /**
  15. * 模型名称
  16. * @var string
  17. */
  18. protected $name = 'cache';
  19. /**
  20. * 获取数据缓存
  21. * @param string $key
  22. * @param $default 默认值不存在则写入
  23. * @return mixed|null
  24. */
  25. public static function getDbCache(string $key, $default, int $expire = self::EXPIRE)
  26. {
  27. self::delectDeOverdueDbCache();
  28. $result = self::where('key', $key)->value('result');
  29. if ($result) {
  30. return json_decode($result, true);
  31. } else {
  32. if ($default instanceof \Closure) {
  33. // 获取缓存数据
  34. $value = $default();
  35. if ($value) {
  36. self::setDbCache($key, $value, $expire);
  37. return $value;
  38. }
  39. } else {
  40. self::setDbCache($key, $default, $expire);
  41. return $default;
  42. }
  43. return null;
  44. }
  45. }
  46. /**
  47. * 设置数据缓存存在则更新,没有则写入
  48. * @param string $key
  49. * @param string | array $result
  50. * @param int $expire
  51. * @return void
  52. */
  53. public static function setDbCache(string $key, $result, $expire = self::EXPIRE)
  54. {
  55. self::delectDeOverdueDbCache();
  56. $addTime = $expire ? time() + $expire : 0;
  57. if (self::be(['key' => $key])) {
  58. return self::where(['key' => $key])->update([
  59. 'result' => json_encode($result),
  60. 'expire_time' => $addTime,
  61. 'add_time' => time()
  62. ]);
  63. } else {
  64. return self::create([
  65. 'key' => $key,
  66. 'result' => json_encode($result),
  67. 'expire_time' => $addTime,
  68. 'add_time' => time()
  69. ]);
  70. }
  71. }
  72. /**
  73. * 删除失效缓存
  74. */
  75. public static function delectDeOverdueDbCache()
  76. {
  77. self::where('expire_time', '<>', 0)->where('expire_time', '<', time())->delete();
  78. }
  79. /**
  80. * 删除某个缓存
  81. * @param string $key
  82. */
  83. public static function delectDbCache(string $key = '')
  84. {
  85. if ($key)
  86. return self::where('key', $key)->delete();
  87. else
  88. return self::delete();
  89. }
  90. }