我正在探索Laravel的雄辯作爲我的項目當前的本土活動記錄數據層的替代品。目前,我有一個類User
,支持與另一個類的多對多關係,Group
。我目前的實現看起來是這樣的:雄辯處理相關實體的緩存嗎?
class User {
protected $_groups; // An array of Group objects to which this User belongs
public function __construct($properties = []){
...
}
public function groups() {
if (isset($_groups))
return $_groups;
else
return $_groups = fetchGroups();
}
private function fetchGroups() {
// Lazily load the associated groups based on the `group_user` table
...
}
public function addGroup($group_id) {
// Check that the group exists and that this User isn't already a member of the group. If so, insert $group_id to $_groups.
...
}
public function removeGroup($group_id) {
// Check that the User is already a member of the group. If so, remove $group_id from $_groups.
...
}
public function fresh() {
// Reload user and group membership from the database into this object.
...
}
public function store() {
// Insert/update the user record in the `user` table, and insert/update/delete records in `group_user` based on the contents of `$_group_user`.
...
}
public function delete() {
// If it exists, delete the user record from the `user` table, and delete all associated records in `group_user`.
...
}
}
正如你所看到的,我的課:
- 執行與集團的延遲加載,他們查詢後的第一次高速緩存;
- 保持
User
與其Group
的關係的內部表示,僅當調用store
時纔在數據庫中更新; - 在建立關係時執行健全性檢查,確保
Group
存在並且在創建新關聯之前尚未與User
相關聯。
哪個,如果有這些東西,會雄辯自動照顧我嗎?或者,我的設計在某種程度上有缺陷,是雄辯所能解決的?
你可以假設我將重新實現User
爲User extends Illuminate\Database\Eloquent\Model
,用洋洋灑灑的belongsToMany
爲我目前fetchGroups
方法的替代品。
非常有趣!因此,在某些方面,Eloquent與我的模型做了相反的事情 - 雄辯的行爲立即在數據庫上,但不更新對象的狀態,直到我調用「fresh」爲止,而我的模型立即作用於對象,但沒有更新數據庫,直到我調用'store'。 – alexw
非常漂亮!不過,如果你願意的話,你可以選擇立即在對象上工作,並在'store()'上更新數據庫。只需要編寫更多的代碼,而不是利用開箱即用的功能。既然你已經選擇了一個API,你可以用任何有意義的方式抽象出這個功能。 –
謝謝。我會繼續前進,現在用Eloquent重新實現我目前的設計。如果在以後的道路上我意識到Eloquent的本地方法更好,那麼就這樣吧;-) – alexw