MenuService.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace Longyi\DynamicMenu\Services;
  3. use Longyi\DynamicMenu\Models\MenuItem;
  4. use Illuminate\Support\Facades\Cache;
  5. class MenuService
  6. {
  7. public function boot()
  8. {
  9. // ... 其他代码
  10. Event::listen('bagisto.admin.menu.build', function ($menu) {
  11. $settings = $menu->get('settings');
  12. if ($settings) {
  13. // 使用缓存,避免每次请求都查询数据库
  14. $menuItems = Cache::remember('dynamic_menu_items', 3600, function () {
  15. return app(MenuService::class)->getEnabledMenuItems();
  16. });
  17. foreach ($menuItems as $item) {
  18. $this->addMenuItemToMenu($settings, $item);
  19. }
  20. }
  21. });
  22. }
  23. /**
  24. * 获取所有启用的菜单项
  25. */
  26. public function getEnabledMenuItems()
  27. {
  28. return MenuItem::with('children')
  29. ->whereNull('parent_id')
  30. ->where('status', 1)
  31. ->orderBy('sort_order')
  32. ->get();
  33. }
  34. /**
  35. * 清除菜单缓存
  36. */
  37. public function clearCache()
  38. {
  39. Cache::forget('dynamic_menu_items');
  40. }
  41. }