| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- <?php
- namespace Longyi\DynamicMenu\Services;
- use Longyi\DynamicMenu\Models\MenuItem;
- use Illuminate\Support\Facades\Cache;
- class MenuService
- {
- public function boot()
- {
- // ... 其他代码
- Event::listen('bagisto.admin.menu.build', function ($menu) {
- $settings = $menu->get('settings');
-
- if ($settings) {
- // 使用缓存,避免每次请求都查询数据库
- $menuItems = Cache::remember('dynamic_menu_items', 3600, function () {
- return app(MenuService::class)->getEnabledMenuItems();
- });
-
- foreach ($menuItems as $item) {
- $this->addMenuItemToMenu($settings, $item);
- }
- }
- });
- }
- /**
- * 获取所有启用的菜单项
- */
- public function getEnabledMenuItems()
- {
- return MenuItem::with('children')
- ->whereNull('parent_id')
- ->where('status', 1)
- ->orderBy('sort_order')
- ->get();
- }
-
- /**
- * 清除菜单缓存
- */
- public function clearCache()
- {
- Cache::forget('dynamic_menu_items');
- }
- }
|