تخيل إنه لدينا بعض الدوال في الـ Controller تقوم بعمل تنسيق معين للبيانات، ونريد إستخدامها في Controllers أخرى.
Bad Practice Example
class NotificationController extends Controller
{
public static function formatNotifications()
{
return Notification::orderBy('created_at', 'desc')
->get(['id', 'content', 'created_at'])
->map(function($item) {
return [
'id' => $item['id'],
'content' => $item['content'],
'created_at' => $item['created_at']->diffForHumans()
];
});
}
public function index()
{
return view('notifications', [
// it is relatively ok to call the method from the same controller
'notifications' => self::formatNotifications();
]);
}
}
class HomeController extends Controller
{
public function index()
{
return view('index', [
'reffered_users' => User::where('referred_by', auth()->id())->count(),
// But it's VERY bad to call Controller method from another Controller
'notifications' => NotificationController::formatNotifications()
]);
}
}What To Do Instead
// Separate NotificationService:
namespace App\Services;
class NotificationService
{
public function formatNotifications(){
return Notification::orderBy('created_at', 'desc')
->get(['id', 'content', 'created_at'])
->map(function($item) {
return [
'id' => $item['id'],
'content' => $item['content'],
'created_at' => $item['created_at']->diffForHumans()
];
});
}
}
// Controller 1:
class NotificationController extends Controller
{
public function index(NotificationService $notificationService)
{
return view('notifications', [
'notifications' => $notificationService->formatNotifications();
]);
}
}
// Controller 2:
use App\Services\NotificationService;
class HomeController extends Controller
{
public function index(NotificationService $notificationService)
{
return view('index', [
'reffered_users' => User::where('referred_by', auth()->id())->count(),
'notifications' => $notificationService->formatNotifications()
]);
}
}الـ Controllers بشكل عام يجب ان يكون خفيف قدر الإمكان، ويجب أن لا يحتوي على business logic، ذلك يعني أن أي دوال أخرى ( مشتركة ...)، يجب أن يتم وضعها في مكان ما مثل Service Class، وهذا الكلاس يمكن إستخدامة في أي Controller
زائر
صح لسانك