我应该在哪里编写结合两个模型的控制器逻辑 [英] Where should I write controller logic that combines two models

查看:71
本文介绍了我应该在哪里编写结合两个模型的控制器逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有PostController和CommentController,当然我有Post模型和Comment模型.因此,现在我收到请求对Post和Comment模型进行一些修改的请求(也许此修改逻辑不仅结合了两个模型,而且还合并了3、4、5或更多模型),所以在Post或Comment中编写逻辑应该是不正确的控制器.那么我应该在哪里写这个逻辑呢?我应该新建控制器吗?

Imagine I have PostController and CommentController, of course I have Post model and Comment model. So now I receive request to make some modifications for both Post and Comment model (maybe this modification logic combines not only two models but 3, 4, 5 or even more), so It shouldn't be right to write logic In Post or Comment controllers. So where should I write this logic? should I make new controller?

推荐答案

您必须尝试使用​​存储库模式.

You must try the repository pattern.

这种模式的思想是将逻辑层与控制器分开,每个模型都有一个带有逻辑的存储库,每个逻辑层,每个存储库也可以有另一个层来将查询保存到数据库(数据库)层).

The idea of this pattern is to separe the layer of logic from the controllers, every model has a repository with his logic, also every logic layer, every repo, can have another layer to hold the queries to the DB (a database layer).

然后,您可以将该存储库插入控制器中,将槽依赖性注入插入每个控制器的构造函数中,控制器中的代码更少,逻辑更具可测试性,并且可以在多个控制器中共享逻辑无需重复.

Then you can insert that repositories in the controllers, trough dependency injection in the constructor of each one, you'll have less code in the controllers, the logic is more testeable, and you can share the logic in more than one controller without repeating it.

查看此帖子:

  • https://medium.com/@jsdecena/refactor-the-simple-tdd-in-laravel-a92dd48f2cdd
  • https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/

这篇关于我应该在哪里编写结合两个模型的控制器逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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