MVC:模型视图控制器 - 视图调用模型? [英] MVC: Model View Controller -- does the View call the Model?

查看:214
本文介绍了MVC:模型视图控制器 - 视图调用模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关MVC设计的一段时间,并且正式地在View中调用了Model中的对象和方法,构建并输出了一个视图。

I've been reading about MVC design for a while now and it seems officially the View calls objects and methods in the Model, builds and outputs a view.

我认为这主要是错误的。

I think this is mainly wrong.

控制器应该对模型内部的对象进行操作和检索/更新,然后选择适当的视图并将信息传递给它,以便可能显示。只有粗体和简约的PHP变量/简单的if语句应该出现在View中。

The Controller should act and retrieve/update objects inside the Model, select an appropriate View and pass the information to it so it may display. Only crude and rudiementary PHP variables/simple if statements should appear inside the View.

如果View获取了需要从Model显示的信息,肯定会有视图中的很多PHP - 完全违反分离表示逻辑的点。

If the View gets the information it needs to display from the Model, surely there will be a lot of PHP inside the View -- completely violating the point of seperating presentation logic.

推荐答案

与所有的程序一样,我们需要务实。视图只应包含演示逻辑。这个逻辑可能非常简单或者可能相当复杂。只要该逻辑只处理屏幕上显示的内容,打印在报表上等。

As with all things programming we need to be pragmatic. A view should only contain presentation logic. That logic can be very simple or can be quite complex. As long as that logic only handles what is displayed on the screen, printed on the report, etc.


控制器应该执行并检索/更新模型中的对象,选择一个适当的视图并将信息传递给它,以便可能显示。

The Controller should act and retrieve/update objects inside the Model, select an appropriate View and pass the information to it so it may display.

这是什么信息通过?可能是模型的一个子集。您可以创建一个仅包含视图应该知道的信息或仅传递模型的新类,并确保只访问适当的数据。无论如何,视图应该可以自由地查询在模型中传递的能够显示视图的视图。

What is this information you are passing? Possibly a subset of a model. You could create a new class containing only the information the view should know about or just pass along the model and make sure you only access appropriate data. Anyway, the view should be free to query this passed in model to be able to display a view.

争议点是如果您从视图中可以直接更新模型,绕过控制器。这是务实的一面。我认为有些情况可以直接更新模型。特别是如果可以使用数据绑定。您可以将文本框分配给模型的属性,并使更新自动进行。如果有很多简单的属性设置,这种方法可以在控制器中保存一堆代码。 MVC不是一整套规则。这是指导,当正确使用可以产生更好的代码,但如果使用太严格可导致痛苦和痛苦。

The point of controversy is if you from the view should be able to update the model directly, bypassing the controller. This is where the pragmatic side comes in. I think there are cases that can warrant updating the model directly. Especially if you can use data bindings. The you can assign a text box to a property of the model and let the update automagically happen. If there are a lot of simple property setting this approach can save a bunch of code in the controller. MVC is not a set of rules set in stone. It's guidelines that when used correctly can produce better code but if used too rigorously can lead to pain and suffering.

务实!

这篇关于MVC:模型视图控制器 - 视图调用模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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