MVC:模型视图控制器——视图调用模型吗?
我已经阅读了一段时间关于 MVC 设计的文章,似乎正式视图调用模型中的对象和方法,构建并输出视图.
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 语句.
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中得到了它需要显示的信息,那么View里面肯定会有很多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.
务实!
相关文章