為了更好的演示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的一個過程。