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中文网其他相关文章!