1
我想知道laravel 5中Models和Repository之間有什麼區別。兩者是否相同,以及存儲庫的好處是什麼。laravel 5中的Models和Repository有什麼區別?
我想知道laravel 5中Models和Repository之間有什麼區別。兩者是否相同,以及存儲庫的好處是什麼。laravel 5中的Models和Repository有什麼區別?
模型和存儲庫不相同。
從documentation - Models allow you to query for data in your tables, as well as insert new records into the table.
這是什麼意思,是模型打開訪問數據庫表。它還允許您與其他模型進行關聯,以便無需編寫單個查詢即可提取數據。
存儲庫允許您處理模型,而無需在控制器內編寫大量查詢。反過來,如果出現任何錯誤,保持代碼更整潔,模塊化且更易於調試。
您可以通過以下方式使用存儲庫:
public function makeNotification($class, $title, $message)
{
$notification = new Notifications;
...
$notification->save();
return $notification->id;
}
public function notifyAdmin($class, $title, $message)
{
$notification_id = $this->makeNotification($class, $title, $message);
$users_roles = RolesToUsers::where('role_id', 1)->orWhere('role_id', 2)->get();
$ids = $users_roles->pluck('user_id')->all();
$ids = array_unique($ids);
foreach($ids as $id) {
UserNotifications::create([
'user_id' => $id,
'notification_id' => $notification_id,
'read_status' => 0
]);
}
}
而且控制器內部:
protected $notification;
public function __construct(NotificationRepository $notification)
{
$this->notification = $notification;
}
public function doAction()
{
...
$this->notification->notifyAdmin('success', 'User Added', 'A new user joined the system');
...
}