为什么要把MVC中的View拆分成一个视图类和一个模板

我对设计模式比较陌生,但我觉得我对 MVC 模式以及这种代码分离带来的优势有了很好的理解.

I'm relatively new to design patterns but I feel that I've got a good understanding of the MVC pattern and the advantages that this separation of code brings.

然而,两次我都看到了 MVC 模式的实际应用(Magento 和 Joomla!),还有进一步的专业化,view 包含一个视图类(Magento 块)和一个PHP 模板文件.如果有人能解释这种拆分的好处,我将不胜感激.

However, both times I've seen the MVC pattern in action (Magento and Joomla!), there is further specialization, with the view consisting of both a view class (Magento block) and a PHP template file. I would appreciate it if someone could explain the benefit of this split.

我也不知道如何在视图类和模板文件之间拆分我的代码.有时我发现自己写了一个看似多余的视图类(在 Joomla 中!),它只是访问模型,然后只为模板提供数据.模板中应该出现哪些代码,视图类中应该出现哪些代码?

I'm also at a loss as to how to split my code between the view class and the template file. Sometimes I find myself writing what seems to be a redundant view class (in Joomla!) which simply accesses the model and then just makes the data available for the template. What code should appear in the template and what code should appear in the view class?

推荐答案

View,在受 MVC 启发的设计模式中,负责所有的 UI 逻辑.他们应该从模型层请求信息,并根据他们收到的信息选择应该使用哪些模板来创建响应.或者即使需要任何渲染(视图也可以只发送 HTTP 标头).

View, in MVC-inspired design patterns, are responsible for all of you UI logic. They should be requesting information from model layer and, based on what they receive, choosing which templates should be used for creation of the response. Or even if any rendering is required (view can just as well just send a HTTP header).

你可以说在经典的MVC和Model2 MVC模式中,视图只从模型层读取,而控制器只向它写入.

如果您从模型层收到一些错误状态,则视图采用主布局模板并补充它的模板,其中包含错误消息的 HTML 片段.然后它组装整个内容并显示给用户(在 Web 应用程序的情况下是浏览器).

If you receive some error state from model layer, the view takes the main layout template and supplements it template, which is contains HTML fragment for error messages. Then it assembles the whole thing an shows to the user (which, in case of web applications is the browser).

模板,在您的基本 Web 应用程序中,只是混合了标签和 php 变量的简单文件.

Templates, in your basic web application, are just simple files with a mix of tags and php variables.

相关文章