| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- <?php
- namespace Longyi\DynamicMenu\Providers;
- use Illuminate\Support\ServiceProvider;
- use Illuminate\Support\Facades\Cache;
- use Longyi\DynamicMenu\Models\MenuItem;
- class DynamicMenuServiceProvider extends ServiceProvider
- {
- public function boot()
- {
- // 加载迁移
- $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
- // 加载路由
- $this->loadRoutesFrom(__DIR__ . '/../Routes/admin-routes.php');
- // 加载视图
- $this->loadViewsFrom(__DIR__ . '/../Resources/views', 'dynamicmenu');
- // 加载语言文件
- $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'dynamicmenu');
- // 发布资源
- $this->publishes([
- __DIR__ . '/../../publishable/assets' => public_path('vendor/dynamicmenu'),
- ], 'public');
- }
- public function register()
- {
- // 延迟合并配置,等到服务提供者注册完成后
- $this->app->booted(function () {
- $this->mergeDynamicMenuConfig();
- });
- if ($this->app->runningInConsole()) {
- $this->commands([
- \Longyi\DynamicMenu\Console\Commands\InitializeSettings::class,
- ]);
- }
- }
- /**
- * 合并动态菜单配置
- */
- protected function mergeDynamicMenuConfig()
- {
- try {
- // 从数据库获取菜单配置
- $menuConfig = $this->getMenuConfigFromDatabase();
- // 获取现有配置
- $existingConfig = $this->app['config']->get('menu.admin', []);
- // 合并配置
- $mergedConfig = array_merge($existingConfig, $menuConfig);
- // 设置配置
- $this->app['config']->set('menu.admin', $mergedConfig);
- } catch (\Exception $e) {
- \Log::error('合并动态菜单配置失败: ' . $e->getMessage());
- }
- }
- /**
- * 从数据库获取菜单配置
- */
- protected function getMenuConfigFromDatabase($useCache = true)
- {
- if (!$useCache) {
- // 不使用缓存,直接查询数据库
- $menuItems = MenuItem::with('children')
- ->where('status', 1)
- ->orderBy('sort_order')
- ->get();
- return $this->buildMenuConfig($menuItems);
- }
- // 使用缓存
- return Cache::remember('dynamic_menu_config', 3600, function () {
- try {
- $menuItems = MenuItem::with('children')
- ->where('status', 1)
- ->orderBy('sort_order')
- ->get();
- return $this->buildMenuConfig($menuItems);
- } catch (\Exception $e) {
- \Log::warning('无法从数据库获取菜单:' . $e->getMessage());
- return [];
- }
- });
- }
- // ... existing code ...
- /**
- * 构建菜单配置数组
- */
- protected function buildMenuConfig($menuItems)
- {
- $config = [];
- foreach ($menuItems as $item) {
- $menuItem = [
- 'key' => $item->key,
- 'name' => $item->name,
- 'route' => $item->route ?: 'admin.dynamicmenu.index',
- 'sort' => (int) $item->sort_order,
- 'icon' => $item->icon ?: 'icon-menu',
- ];
- $config[] = $menuItem;
- }
- return $config;
- }
- }
|