UserInfoCache.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | saiadmin [ saiadmin快速开发框架 ]
  4. // +----------------------------------------------------------------------
  5. // | Author: sai <1430792918@qq.com>
  6. // +----------------------------------------------------------------------
  7. namespace plugin\saiadmin\app\cache;
  8. use plugin\saiadmin\app\model\system\SystemUser;
  9. use support\Cache;
  10. /**
  11. * 用户信息缓存
  12. */
  13. class UserInfoCache
  14. {
  15. private string $prefix = 'user_info_'; // 缓存前置
  16. private string $cacheUserKey = ''; // 管理员缓存key
  17. private string $adminId = ''; // 管理员id
  18. /**
  19. * 初始化
  20. * @param string $adminId
  21. */
  22. public function __construct(string $adminId = '')
  23. {
  24. $this->adminId = $adminId;
  25. $this->cacheUserKey = $this->prefix . $this->adminId;
  26. }
  27. /**
  28. * 通过id获取缓存管理员信息
  29. */
  30. public function getUserInfo()
  31. {
  32. // 直接从缓存获取
  33. $adminInfo = Cache::get($this->cacheUserKey);
  34. if ($adminInfo) {
  35. return $adminInfo;
  36. }
  37. // 获取信息并返回
  38. $adminInfo = $this->setUserInfo();
  39. if ($adminInfo) {
  40. return $adminInfo;
  41. }
  42. return false;
  43. }
  44. /**
  45. * 设置管理员信息
  46. */
  47. public function setUserInfo(): array
  48. {
  49. $admin = SystemUser::where('id', $this->adminId)->findOrEmpty();
  50. $data = $admin->hidden(['password'])->toArray();
  51. $data['roleList'] = $admin->roles->toArray() ?: [];
  52. $data['postList'] = $admin->posts->toArray() ?: [];
  53. $data['deptList'] = $admin->depts ? $admin->depts->toArray() : [];
  54. // 保存到缓存
  55. Cache::set($this->cacheUserKey, $data, 3600);
  56. return $data;
  57. }
  58. /**
  59. * 清理管理员信息缓存
  60. */
  61. public function clearUserInfo(): bool
  62. {
  63. Cache::delete($this->cacheUserKey);
  64. return true;
  65. }
  66. }