为了更好的演示MVC的工作方式,我们使用了一个简单的新闻文章发布系统作为例子。分为使用MVC和不使用MVC两种方式。我们只作一个基本的演示,从数据库里读出一些文章列表,并在页面上显示。一般的流程就是,连接数据库,查询数据库,循环输出html结果。下面的代码就是如此做的。
<?php
mysql_connect(…);
$result = mysql_query('select * from news order by article_date desc');
?>
<html>
<body>
<h1>News Articles</h1>
<?php while ($row = mysql_fetch_object($result)) { ?>
<h2><?php echo $row->headline ?></h2>
<p>
<?php echo $row->body ?>
</p>
<?php } ?>
</body>
</html>
采用MVC方式则如下。
model:
<?php
function get_articles()
{
mysql_connect(…);
$result = mysql_query('select * from news order by article_date desc');
$articles = array();
while ($row = mysql_fetch_objects($result)) {
$articles[] = $row;
}
return $articles;
}
?>
controller:
<?php
$articles = get_articles();
display_template('articles.tpl');
?>
view:
<html>
<body>
<h1>News Articles</h1>
<?php foreach ($articles as $row) { ?>
<h2><?php echo $row->headline ?></h2>
<p>
<?php echo $row->body ?>
</p>
<?php } ?>
</body>
</html>
将PHP代码直接写到HTML文件中,感觉不是很专业,也不安全。使用MVC会遇到其他一些问题,比如模板解析、路由转发等,不过这些都是后话了。这里只是简单演示下MVC的一个过程。