[英]How to fill a custom object via the repository pattern and Laravel's Eloquent
好的,這是交易。 我正在使用自定義CMS,我希望代碼盡可能優化。 我一直在閱讀/觀看tuts / etc。 就像對存儲庫模式大為瘋狂,以及對Laravel的Eloquent專門使用它一樣。 這里可能有一些非常愚蠢的問題/想法,但請忍受。 :-)有時候,如果沒有傻話,就沒有簡單的方法來詢問術語/最佳實踐。
與許多事情一樣,我有數百萬種方法可以使其“發揮作用”。 我的困境本質上是“最佳實踐”的問題。
一般情況/問題
假設我正在嘗試從數據庫獲取CMS的Page 。 據我了解,使用Eloquent設置repository pattern
的典型方法是擁有以下文件:
很簡單。 所以我可能會用這種方式。 假設我有一個getPageById
的方法EloquentPageRepository.php
,我可以做這樣的事情從我的控制器:
$page = $this->repo->getPageById();
現在我的問題出現了:getPageById()應該返回什么類型的數據? 有人建議將其設置為返回Eloquent集合。 其他人則只是說一個普通數組或通用對象。
理想情況下,我覺得我的場景最適合讓EloquentPageRepository
從Eloquent抓取數據並實際上返回我擁有的自定義Page類的實例。 例如,與此類似的東西:
<?php namespace Acme\Repositories\EloquentPageRepository;
use Acme\...\PageObject as PageObject; // Better name than PageObject?
//...
class EloquentPageRepository implements PageRepositoryInterface {
// Omitting constructor, etc.
public function getPageById($id)
{
// Grab the row via Eloquent (obviously not stored in Page:: at
// this point. I'm just using it here for clarity and time's sake.
$page = Page::find($id);
// Now we have an Eloquent collection stored in $page, but I'd
// like to return the data inside an instance of my custom class.
$pageObj = new PageObject($page->title, $page->body);
return $pageObj;
}
}
在我看來,這似乎很好,因為它在回購之間提供了一致的交付格式。 它還允許我在pageObject上執行一些構造函數邏輯。 最后,它允許我在PageObject上有一些自定義方法(與存儲庫無關)。
它類似於一個收藏,但是我不認為是那樣。 基本上,這只是我立即用數據庫信息填充的類的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.