基本 MVC (PHP) 结构

时间:2023-01-03
本文介绍了基本 MVC (PHP) 结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

对于一个简单的登录表单,我有以下数据流.

I have the following data flow for a simple login form.

用户访问控制器 PHP 文件.控制器包括model.php和view.php

User access controller PHP file. Controller includes model.php and view.php

用户提交表单,控制器将 POST 数据发送到模型方法,并返回结果.

User submits form, controller sends POST data to model methods, and gets a result back.

用户已登录,并由控制器转发到不同的视图(登录成功消息).

User is logged in, and forwarded to a different view (login success message) by the controller.

目前我的视图是静态 HTML(没有 PHP),所以这是我的问题.然后向用户传递欢迎消息的正确方法是什么,例如你好,克雷格!"?

Currently my views are static HTML (no PHP), so here is my question. What is the correct way to then pass the user a welcome message, e.g "Hello, Craig!"?

视图是否允许 PHP 片段,例如

Is the view allowed PHP snippets, e.g

<?php echo $username; ?> 

因为模型是在控制器文件中先加载的吗?

since the model is loaded before it in the controller file?

谢谢!

允许视图访问特定的类方法(例如

Is it better practice then to allow the view to access specific class methods e.g

<?php $user->getUsername(); ?>

而不仅仅是变量?

根据其他答案,我找到了一篇非常有用的文章,您可能也感兴趣.

Based on other answers, I have found a very useful article, which you may also be interested in.

http://www.nathandavison.com/posts/view/7/custom-php-mvc-tutorial-part-5-views

推荐答案

你真的可以把任何你想要的东西放在一个视图中,但是为了更好地遵循 MVC 的做事方式,你应该将视图中的 PHP 限制为简单的 echos 或 prints(也可能是非常小的循环,尽管这些循环也可以在控制器/模型中预先计算).由于这是获取动态内容的唯一方法,所以说它们是不允许的就有点傻了.

You can really put anything in a view that you'd like, but to better adhere to the MVC way of doing things you should restrict PHP in the view to simple echos or prints (possibly really small loops as well, although even those can be pre-calculated in the controller/model). Since that is the only way to get dynamic content, it would be a little silly to say that they are not allowed.

视图的想法是让它具有更多的 HTML 外观,以便前端开发人员或不了解 PHP 的人可以轻松地使用该文件而不会感到困惑.

The idea of the view is to let it have a more HTML look-and-feel, so that front-end developers or people who don't know PHP can easily be able to work with the file without getting confused.

更新

要了解有关 MVC 的更多信息,您可以查看其中任何一个(有大量教程):

To learn more about MVC in general, you can see any of these (there's a ton of tutorials out there):

http://blog.iandavis.com/2008/12/09/what-are-the-benefits-of-mvc/

http://php-html.net/tutorials/model-view-controller-in-php/

http://www.tonymarston.net/php-mysql/模型视图控制器.html

要查看使用 MVC 的 PHP 的具体示例,我建议下载一些更流行的框架(例如 CodeIgniter,Symfony 或 Drupal) 并查看代码.尝试弄清楚它是如何工作的,然后为一个简单的基于文章的系统重新创建功能.

To see concrete examples of PHP using MVC, I suggest downloading some of the more prevelant frameworks (such as CodeIgniter, Symfony or Drupal) and just looking through the code. Try to figure out how it works and then recreate the functionality for a simple article-based system.

这篇关于基本 MVC (PHP) 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:MVC中数据访问层和模型的区别 下一篇:Symfony2 禁用缓存?

相关文章

最新文章