CacheService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2018/01/05
  6. */
  7. namespace crmeb\services;
  8. use think\facade\Cache as CacheStatic;
  9. /**
  10. * crmeb 缓存类
  11. * Class CacheService
  12. * @package crmeb\services
  13. */
  14. class CacheService
  15. {
  16. /**
  17. * 标签名
  18. * @var string
  19. */
  20. protected static $globalCacheName = '_cached_1515146130';
  21. /**
  22. * 写入缓存
  23. * @param string $name 缓存名称
  24. * @param $value 缓存值
  25. * @param int $expire 缓存时间,为0读取系统缓存时间
  26. * @return bool
  27. */
  28. public static function set(string $name, $value, int $expire = 0): bool
  29. {
  30. //这里不要去读取缓存配置,会导致死循环
  31. $expire = $expire ?: SystemConfigService::get('cache_config', null, true);
  32. if (!is_int($expire))
  33. $expire = (int)$expire;
  34. return self::handler()->set($name, $value, $expire);
  35. }
  36. /**
  37. * 如果不存在则写入缓存
  38. * @param string $name
  39. * @param bool $default
  40. * @return mixed
  41. */
  42. public static function get(string $name, $default = false)
  43. {
  44. return self::handler()->remember($name, $default);
  45. }
  46. /**
  47. * 删除缓存
  48. * @param string $name
  49. * @return mixed
  50. */
  51. public static function rm(string $name)
  52. {
  53. return self::handler()->remember($name, '');
  54. }
  55. /**
  56. * 删除缓存
  57. * @param string $name
  58. * @return bool
  59. * @throws \Psr\SimpleCache\InvalidArgumentException
  60. */
  61. public static function delete(string $name)
  62. {
  63. return CacheStatic::delete($name);
  64. }
  65. /**
  66. * 缓存句柄
  67. * @return \think\cache\TagSet
  68. */
  69. public static function handler()
  70. {
  71. return CacheStatic::tag(self::$globalCacheName);
  72. }
  73. /**
  74. * 清空缓冲池
  75. * @return bool
  76. */
  77. public static function clear()
  78. {
  79. return self::handler()->clear();
  80. }
  81. }