Laravel視圖創建器允許您在視圖實例化後立即準備數據,比視圖組合器更早,這使得它們非常適合設置必要的視圖數據或優化性能。
讓我們來看一個管理動態應用程序菜單的實用示例:
首先,註冊視圖創建器:
use Illuminate\Support\Facades\View; // 注册视图创建器 View::creator('dashboard', DashboardCreator::class);
接下來,定義視圖創建器類:
<?php namespace App\View\Creators; use App\Services\MenuService; use Illuminate\View\View; use Illuminate\Support\Facades\Auth; class ApplicationMenuCreator { protected $menuService; public function __construct(MenuService $menuService) { $this->menuService = $menuService; } public function create(View $view) { $user = Auth::user(); $view->with([ 'mainMenu' => $this->menuService->getMainMenu($user), 'quickActions' => $this->menuService->getQuickActions($user), 'recentItems' => $this->menuService->getRecentItems($user), 'notifications' => $this->menuService->getPendingNotifications($user) ]); } }
在你的AppServiceProvider
中註冊視圖創建器:
// 在你的 AppServiceProvider public function boot() { View::creator('layouts.app', ApplicationMenuCreator::class); }
最後,在layouts/app.blade.php
中使用數據:
<div class="sidebar"> <nav> @foreach($mainMenu as $menuItem) <a class="https://www.php.cn/link/a754fc1765a45a6bc1a034140afd0669'active'] ? 'active' : '' }}" href="https://www.php.cn/link/a754fc1765a45a6bc1a034140afd0669'url'%5D%20%7D%7D"> https://www.php.cn/link/a754fc1765a45a6bc1a034140afd0669'label'] }} </a> @endforeach </nav> @if(count($quickActions)) <div class="quick-actions"> @foreach($quickActions as $action) {{ $action['label'] }} @endforeach </div> @endif </div>
視圖創建器為您的視圖提供早期數據準備,確保關鍵數據在視圖實例化後立即可用。 這有助於提高應用程序性能和代碼可維護性。
以上是Laravel View創建者的早期查看數據準備的詳細內容。更多資訊請關注PHP中文網其他相關文章!