問題描述
對于一個簡單的登錄表單,我有以下數據流.
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 限制為簡單的 echo
s 或 print
s(也可能是非常小的循環,盡管這些循環也可以在控制器/模型中預先計算).由于這是獲取動態內容的唯一方法,所以說它們是不允許的就有點傻了.
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 echo
s or print
s (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) 結構的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!