我正在尝试学习存储库模式,但似乎对如何在急切加载关系时使用此存储库模式并将数据库逻辑保持在我的 Controller 之外感到困惑。
我的存储库/应用程序结构的快速概览。
app/
Acme/
Repositories/
RepositoryServiceProvider.php
Product/
EloquentProduct.php
ProductInterface.php
Category/
EloquentCategory.php
CategoryInterface.php
示例 ProductInterface.php
<?php namespace GD\Repositories\Product;
interface ProductInterface
{
public function all();
public function find($id);
public function findBySlug($slug);
}
示例 CategoryInterface.php
<?php namespace GD\Repositories\Category;
interface CategoryInterface
{
public function all();
public function find($id);
public function findBySlug($slug);
}
好的,所以简单的部分是使用 DI 将模型依赖项注入(inject) Controller 。
列出所有类别与相关的产品更加困难,因为我不再使用 Eloquent 模型。我正在使用一个没有公开所有 Eloquent 方法的接口(interface)。
如果没有在我的 EloquentCategory 类中实现 with 方法,这将无法工作...
public function show($slug)
{
return Response::json($this->category->findBySlug($slug)->with('products'), 200);
}
我应该创建一个单独的服务类来将两个存储库粘合在一起吗?例如允许以下
public function __construct(ShopService $shop)
{
$this->shop = $shop;
}
public function show($slug)
{
return Response::json( $this->shop->getProductsInCategory($slug), 200 );
}
或者,我应该在我的类别存储库中实现 with 方法吗?
public function with($relation)
{
return Category::with($relation);
}
最后,我对 Repository Pattern 用法的理解是否正确?
最佳答案
您想多了,存储库只是您的 controller
和 model
之间的链接/桥梁,因此 Controller 使用 repository
类而不是model
直接在该存储库中,您可以使用那里的 model
声明您的方法,例如:
<?php namespace GD\Repositories\Category;
interface CategoryInterFace{
public function all();
public function getCategoriesWith($with);
public function find($id);
}
现在在存储库类中实现接口(interface):
<?php namespace GD\Repositories\Category;
use \EloquentCategory as Cat; // the model
class CategoryRepository implements CategoryInterFace {
public function all()
{
return Cat::all();
}
public function getCategoriesWith($with)
{
return Cat::with($with)->get();
}
public function find($id)
{
return Cat::find($id):
}
}
在你的 Controller 中使用它:
<?php
use GD\Repositories\Category\CategoryInterFace;
class CategoryController extends BaseController {
public function __construct(CategoryInterFace $category)
{
$this->cat = $category;
}
public function getCatWith()
{
$catsProd = $this->cat->getCategoriesWith('products');
return $catsProd;
}
// use any method from your category
public function getAll()
{
$categories = $this->cat->all();
return View::make('category.index', compact('categories'));
}
}
注意:省略了存储库的 IoC
绑定(bind),因为这不是您的问题而且您知道这一点。
更新:我在这里写了一篇文章:LARAVEL – USING REPOSITORY PATTERN .
关于php - Laravel - 使用存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805939/