php – Laravel – 使用存储库模式
发布时间:2020-12-14 19:49:19 所属栏目:大数据 来源:网络整理
导读:我正在尝试学习存储库模式,并且似乎已经让自己感到困惑,当我想要加载关系并将db逻辑从我的控制器中删除时,我可以如何使用这个存储库模式. 我的仓库/应用程序结构的快速概述. app/ Acme/ Repositories/ RepositoryServiceProvider.php Product/ EloquentProdu
我正在尝试学习存储库模式,并且似乎已经让自己感到困惑,当我想要加载关系并将db逻辑从我的控制器中删除时,我可以如何使用这个存储库模式.
我的仓库/应用程序结构的快速概述. app/ Acme/ Repositories/ RepositoryServiceProvider.php Product/ EloquentProduct.php ProductInterface.php Category/ EloquentCategory.php CategoryInterface.php 示例ProductInterface.php <?php namespace GDRepositoriesProduct; interface ProductInterface { public function all(); public function find($id); public function findBySlug($slug); } 示例CategoryInterface.php <?php namespace GDRepositoriesCategory; interface CategoryInterface { public function all(); public function find($id); public function findBySlug($slug); } 好的,所以很容易的部分是使用DI将模型依赖项注入到控制器中. 列出所有类别与相关产品更加困难,因为我不再使用雄辩的模型.我正在使用一个没有公开所有雄辩方法的界面. 如果我没有在我的EloquentCategory类中实现一个方法,这将无法正常工作 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); } 最后,我对存储库模式使用的理解是否正确?
您是在思考,存储库只是控制器和模型之间的链接/桥梁,因此控制器使用存储库类而不是直接使用模型,并且在该存储库中,您可以使用该模型声明您的方法,例如:
<?php namespace GDRepositoriesCategory; interface CategoryInterFace{ public function all(); public function getCategoriesWith($with); public function find($id); } 现在在存储库类中实现接口: <?php namespace GDRepositoriesCategory; 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): } } 在控制器中使用它: <?php use GDRepositoriesCategoryCategoryInterFace; 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绑定,因为这不是您的问题,您知道. 更新:我在这里写了一篇文章:LARAVEL – USING REPOSITORY PATTERN. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |