ConfigCache.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. declare(strict_types=1);
  8. namespace plugin\saiadmin\app\cache;
  9. use plugin\saiadmin\app\logic\system\SystemConfigLogic;
  10. use support\think\Cache;
  11. /**
  12. * 配置缓存
  13. */
  14. class ConfigCache
  15. {
  16. /**
  17. * 读取缓存配置
  18. * @return array
  19. */
  20. public static function cacheConfig(): array
  21. {
  22. return config('plugin.saiadmin.saithink.config_cache', [
  23. 'expire' => 60 * 60 * 24 * 365,
  24. 'prefix' => 'saiadmin:config_cache:config_',
  25. 'tag' => 'saiadmin:config_cache'
  26. ]);
  27. }
  28. /**
  29. * 获取配置信息
  30. */
  31. public static function getConfig(string $code = ''): array
  32. {
  33. if (empty($code)) {
  34. return [];
  35. }
  36. $cache = static::cacheConfig();
  37. // 直接从缓存获取
  38. $config = Cache::get($cache['prefix'] . md5($code));
  39. if ($config) {
  40. return $config;
  41. }
  42. // 设置配置并获取
  43. $config = static::setConfig($code);
  44. if ($config) {
  45. return $config;
  46. }
  47. return [];
  48. }
  49. /**
  50. * 设置配置数据
  51. */
  52. public static function setConfig(string $code): array
  53. {
  54. $cache = static::cacheConfig();
  55. $data = (new SystemConfigLogic())->getData($code);
  56. if (empty($data)) {
  57. return [];
  58. }
  59. $tag = [];
  60. $tag[] = $cache['tag'];
  61. // 保存到缓存
  62. Cache::tag($tag)->set($cache['prefix'] . md5($code), $data, $cache['expire']);
  63. return $data;
  64. }
  65. /**
  66. * 清理单个配置缓存
  67. */
  68. public static function clearConfig(string $code): bool
  69. {
  70. $cache = static::cacheConfig();
  71. return Cache::delete($cache['prefix'] . md5($code));
  72. }
  73. /**
  74. * 清理全部配置缓存
  75. * @return bool
  76. */
  77. public static function clear(): bool
  78. {
  79. $cache = static::cacheConfig();
  80. return Cache::tag($cache['tag'])->clear();
  81. }
  82. }