Tối ưu hoá dữ liệu View với View Composers và View Creators
Khi ứng dụng lớn lên, bạn sẽ nhận thấy có một số dữ liệu luôn lặp lại trên nhiều trang. Ví dụ: Dữ liệu Header, danh mục, thống kê Sidebar. Nếu truyền những thứ này ở mọi hàm show(), index() của Controller thì codebase sẽ phình to không cần thiết.
1. Hạn chế của View::share()
Cách cơ bản nhất để chia sẻ là dùng View::share() tại AppServiceProvider.
View::share('categories', Category::all());
Nhược điểm: Query này chạy ở mọi request, ngay cả với các request AJAX trả về JSON hay trang không hề include Header. Rất tốn tài nguyên!
2. Sử dụng View Composers bằng Closure
View Composers chỉ thực thi việc lấy dữ liệu khi view đó sắp được render.
use Illuminate\Support\Facades\View;
public function boot()
{
View::composer('layouts.sidebar', function ($view) {
$view->with('recentPosts', Post::latest()->take(5)->get());
});
}
Bây giờ chỉ request nào nạp file resources/views/layouts/sidebar.blade.php, truy vấn Post::latest() mới được kích hoạt. Bạn thậm chí có thể gắn Composer cho nhiều View bằng wildcard:
View::composer(['pages.*', 'posts.*'], function ($view) { ... });
3. View Composers bằng Class (Tốt cho dự án lớn)
Thay vì viết Closure dồn đống ở AppServiceProvider, hãy tạo Class riêng: App\View\Composers\SidebarComposer.
namespace App\View\Composers;
use Illuminate\View\View;
use App\Models\Post;
class SidebarComposer
{
public function compose(View $view)
{
$view->with('recentPosts', Post::latest()->take(5)->get());
}
}
Đăng ký class trong Provider:
use App\View\Composers\SidebarComposer;
use Illuminate\Support\Facades\View;
View::composer('layouts.sidebar', SidebarComposer::class);
4. View Creators - khác biệt là gì?
View Composers chạy ngay trước khi View được render. Trong khi đó, View Creators chạy ngay sau khi View được khởi tạo (trước cả khi view con được render và dữ liệu override từ controller được đưa vào).
View::creator('profile', ProfileCreator::class);
Bạn sẽ dùng Creators khi muốn Controller có quyền override (ghi đè) lại các biến mặc định mà view creator cung cấp. Tuy nhiên, 95% trường hợp thực tế, View Composers là thứ bạn cần.
Tóm gọn
- Sử dụng View Composers cho các thành phần như Navigation, Footer, Sidebar, User Panels.
- Luôn cẩn thận với bài toán N+1 Entity và hãy kết hợp Cache trong phương thức
compose()để tạo một trải nghiệm Blog siêu nhanh!