UserMenuCache.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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\SystemMenuLogic;
  10. use plugin\saiadmin\app\model\system\SystemUserRole;
  11. use support\think\Cache;
  12. /**
  13. * 用户菜单缓存
  14. */
  15. class UserMenuCache
  16. {
  17. /**
  18. * 读取缓存配置
  19. * @return array
  20. */
  21. public static function cacheConfig(): array
  22. {
  23. return config('plugin.saiadmin.saithink.menu_cache', [
  24. 'prefix' => 'saiadmin:menu_cache:user_',
  25. 'expire' => 60 * 60 * 24 * 7,
  26. 'tag' => 'saiadmin:menu_cache',
  27. ]);
  28. }
  29. /**
  30. * 获取用户的菜单
  31. */
  32. public static function getUserMenu($uid): array
  33. {
  34. if (empty($uid)) {
  35. return [];
  36. }
  37. $cache = static::cacheConfig();
  38. // 直接从缓存获取
  39. $menu = Cache::get($cache['prefix'] . $uid);
  40. if ($menu) {
  41. return $menu;
  42. }
  43. // 设置用户菜单并获取
  44. $menu = static::setUserMenu($uid);
  45. if ($menu) {
  46. return $menu;
  47. }
  48. return [];
  49. }
  50. /**
  51. * 设置用户菜单
  52. */
  53. public static function setUserMenu($uid): array
  54. {
  55. $cache = static::cacheConfig();
  56. $tag = [];
  57. $tag[] = $cache['tag'];
  58. $logic = new SystemMenuLogic();
  59. if ($uid == 1) {
  60. $data = $logic->getAllMenus();
  61. } else {
  62. $roleIds = SystemUserRole::getRoleIds($uid);
  63. $data = $logic->getMenuByRole($roleIds);
  64. if (empty($data)) {
  65. return [];
  66. }
  67. }
  68. // 保存到缓存
  69. Cache::tag($tag)->set($cache['prefix'] . $uid, $data, $cache['expire']);
  70. return $data;
  71. }
  72. /**
  73. * 清理用户缓存
  74. */
  75. public static function clearUserMenu($uid): bool
  76. {
  77. $cache = static::cacheConfig();
  78. return Cache::delete($cache['prefix'] . $uid);
  79. }
  80. /**
  81. * 清理所有菜单缓存
  82. * @return bool
  83. */
  84. public static function clearMenuCache(): bool
  85. {
  86. $cache = static::cacheConfig();
  87. return Cache::tag($cache['tag'])->clear();
  88. }
  89. }