CacheService.php 1.9 KB

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