
[Laravel] Có nên load file helper dựa trên Request trong boot() ❌
private function loadHelperFiles(Request $request)
PHPRủi ro
Request
chưa sẵn sàng khiboot()
chạy, nên việc injectRequest
vàoloadHelperFiles()
sẽ gặp vấn đề tương tự.- Nếu gọi
require_once
quá sớm khi Laravel chưa khởi tạo đủ các component, có thể gây lỗi hoặc làm chậm ứng dụng.
Cách khắc phục ✅
Sử dụng app(Request::class) để lấy request thay vì inject vào method:
private function loadHelperFiles()
{
$request = app(Request::class); // Lấy request an toàn
$prefixes = [
MANAGER_PREFIX => 'managerFunctions.php',
CLIENT_PREFIX => 'clientFunctions.php',
STAFF_PREFIX => 'staffFunctions.php'
];
foreach ($prefixes as $prefix => $file) {
if ($request->is([$prefix, $prefix . '/*'])) {
require_once base_path("app/Helper/{$file}");
break;
}
}
require_once base_path('app/Helper/commonFunctions.php');
}
PHP🔹 Lấy Request từ app() để tránh lỗi injection.
🔹 Nếu helper chỉ cần trong một số route nhất định, bạn nên load chúng trong Middleware thay vì AppServiceProvider.