MVC - 从另一个模型引用一个模型
我的应用程序中有这样的场景:
Controller1
- .GetItems()
模型1
- .GetItems()
Controller2
- .GetCurrentUser()
模型2
- .当前用户
在此场景中,Controller1.GetItems() 调用 Model1.GetItems() 方法。 Model1.GetItems() 方法需要知道(例如)当前用户的角色是什么才能构建正确的项目列表,并且它应该从 Model2.CurrentUser 属性(存储有关当前用户的缓存信息)获取它)。
从另一个模型访问一个模型是一个好习惯吗?
谢谢, 问候
I've this scenario in my application:
Controller1
- .GetItems()
Model1
- .GetItems()
Controller2
- .GetCurrentUser()
Model2
- .CurrentUser
In this scenario Controller1.GetItems() calls Model1.GetItems() method. Model1.GetItems() method needs to know (for example) what is the role of the current user to build the correct list of items, and it should get it from the Model2.CurrentUser property (that stores the cached information about the current user).
Is it a good practice to acces a model from another model?
Thanks,
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将会遇到一些关于最佳方法的争论,但最终,您有两个选择。您可以让模型从其他模型中提取所需的信息,也可以让控制器传递所需的信息。
根据我所读到的内容,只要模型没有任何控制器逻辑或视图逻辑,你就很好,所以让模型了解其他模型没有什么问题。然而,其他人认为让控制器传递所需的信息会使代码更容易记录,因为您可以看到模型需要来自其他地方的信息。但归根结底,我认为两者都是有效的,您选择使用哪一个可能取决于个人喜好。
设计 - 控制器提供数据
代码段 - 控制器提供数据
设计 - 模型获取数据
代码片段 - 模型获取数据
You are going to run into some arguments about the best way to do this, but at the end of the day, you have two options. Either you can have the model pull the information it needs from the other model or you can have the controller pass the information needed.
Based upon what I have read, as long as the model does not have any controller logic or view logic you are good so there is nothing wrong with having the model know about other models. However, others have argued that having the controller pass the information that is needed makes the code a bit easier to document since you can see that the model requires information from somewhere else. At the end of the day though, I see both as being valid and which one you choose to use will likely come down to personal preference.
Design - Controller Provides Data
Snippet - Controller Proivdes Data
Design - Model Gets Data
Snippet - Model Gets Data
如果您的第二个模型经常被第一个模型引用,您可以将模型类编译到单独的库中吗?
If your second model is going to referenced often by your first, you could compile your model classes into a separate library?
我认为您不应该在模型之间进行引用,正确的方法是使用此链接的控制器。因此,在您的情况下,您可以将 CurrentUser 作为 GetItems 方法中的参数传递。
I think you shouldn't have references between models, the right way is to use the controller for this link. So in your case you could pass the CurrentUser as a parameter in the GetItems method.