Laravel存储库 [英] Laravel Repositories

查看:53
本文介绍了Laravel存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel中的存储库有哪些优势?似乎正在从应用程序的业务逻辑中抽象出Model层.尽管这似乎真的使整个请求生命周期变得更加复杂,却几乎没有收益.

What are the advantages of Repositories in Laravel? It seems to be abstracting the Model layer from the business logic of the application. Although it really just seems to make the whole request life cycle just that much more complicated for little gain.

有人可以阐明Laravel存储库的优势吗?

Can someone shed light on the advantage of Laravel repositories?

现在使用存储库一段时间后,我将添加以下内容:

After now using repositories for some time I would add the following:

  • 存储库强制执行单一责任
  • 存储库应仅返回一个实体集合
  • 尽管从依赖注入中分离出的概念是兄弟
  • 实际存储实现(例如MySQL)的存储抽象
  • 更轻松的测试

推荐答案

像提供的教程中一样,存储库不是Laravel概念所必需的.相反,它们是Laravel可以实现的IoC注入形式.任何可能类似注入的对象并不意味着它是一个存储库.观看视频,了解泰勒·奥特威尔(Taylor Otwell)的一个很好的例子,该例子也恰好也使用了存储库": http://vimeo.com/53029232.

Repositories, like in the provided tutorial, aren't necessary a Laravel concept. Rather, they're a form of IoC injection that is possible with Laravel. Any object that might similarly be injected doesn't mean it's a repository. See the video for a good example from Taylor Otwell, which happens to use a "repository" as well: http://vimeo.com/53029232.

在此示例中,存储库对数据的抽象来源进行了传递到控制器.只要传递的数据实现指定的接口,控制器就可以幸福地"使用接口的已定义方法,而不必担心数据最初来自何处.这样就可以在不中断控制器的情况下切换数据的初始来源.您可以从文件,数据库,外部API,模拟对象或只是某些任意数组中提取数据.基本上,控制器不需要收集存储库所表示的数据.它可以接收和使用.

In this example, the repository abstracts where the data came from that is passed to the controller. As long as the data passed implements the specified interface, the controller can "blissfully" make use of the interface's defined methods without worry about where the data initially came from. This allows switching the initial source of the data without breaking your controller. You could pull the data from a file, a database, an outside API, a mock object, or just some arbitrary array. Basically, the controller doesn't need to gather the data represented by the repository. It can just receive and use.

这篇关于Laravel存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆