基本的MVC(PHP)结构 [英] Basic MVC (PHP) Structure

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

问题描述

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

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

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

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

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

该视图是否允许PHP代码段,例如

<?php echo $username; ?> 

因为模型先加载到了控制器文件中?

谢谢!

编辑:然后,允许视图访问特定的类方法(例如

)是一种更好的做法吗?

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

相对于变量?


基于其他答案,我发现了一篇非常有用的文章,您可能也对此感兴趣.

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

解决方案

您确实可以在所需的视图中放置任何内容,但为了更好地遵循MVC的工作方式,应将PHP限制在视图范围内.简单的echo s或print s(也可能是非常小的循环,尽管即使这些循环也可以在控制器/模型中预先计算出).既然这是获取动态内容的唯一方法,那么说不允许它们是有点愚蠢的.

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

更新

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

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

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

http://www.tonymarston.net/php-mysql/model-view-controller.html

要查看使用MVC的PHP的具体示例,建议您下载一些更流行的框架(例如 CodeIgniter Symfony

Is the view allowed PHP snippets, e.g

<?php echo $username; ?> 

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

Thanks!

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

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

as opposed to just variables?


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

解决方案

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.

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.

Update

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/model-view-controller.html

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)结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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