我犹豫回答这个问题只是因为围绕着它的宗教狂热。
要真正了解一般概念背后的问题,请参阅This Wiki Discussion Page 这是围绕 wiki MVC 文章的讨论页面。
这是我喜欢遵循的经验法则(顺便说一句,我使用 CodeIgniter,听起来你也是):
“视图”实际上应该没有逻辑。它应该只是 HTML(在网络世界中)和简单地回显变量的 PHP。在您的示例中,您会将表单分解为自己的视图,控制器将确定是否已加载。
我喜欢这样看:视图不应该知道数据来自哪里或去往哪里。该模型应该与视图无关。控制器将模型中的数据网格化并将其提供给视图 - 它从视图中获取输入并将其过滤到模型中。
这是一个快速而肮脏(未经测试 - 但它应该明白这一点)的例子:
Theapp.php(应用控制器)
class Theapp extends Controller
{
var $_authenticated;
var $_user;
var $_menu; // array of menus
function __construct()
{
session_start();
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'])
{
$this->_authenticated = $_SESSION['authenticated']; // or some such thing
$this->_user = $_SESSION['user'];
}
$this->_menu = array("Logout", "Help", "More");
parent::__construct();
$this->loadView("welcome"); // loads primary welcome view - but not necessarily a complete "html" page
}
function index()
{
if (!$this->_authenticated)
$this->loadView("loginform");
else
{
$viewData['menu'] = $this->_menu;
$viewData['user'] = $this->_user;
$this->loadView("menu", $viewData);
}
}
function login()
{
/* code to authenticate user */
}
function Logout() { /* code to process Logout menu selection */ }
function Help() { /* code to process Help menu selection */ }
function More() { /* code to process More menu selection */ }
}
welcome.php
<h1> Welcome to this quick and dirty app!</h1>
All sorts of good HTML, javascript, etc would be put in here!
loginform.php
<form action"/Theapp/login" method="post">
User: <input id='user' name='user'>
Pass: <input id='pass' name='pass' type='password'>
<input type='submit'>
</form>
menu.php
Hi <?= $user ?>!<br>
Here's your menu<br>
<? foreach ($menu as $option) { ?>
<div class='menuOption'><a href='/Theapp/<?=$option?>'><?=$option?></a></div>
<? } ?>
希望这会有所帮助。