Bookmark and Share

Lee's 程序人生

HTML CSS Javascript XML AJAX ATLAS C# C++ 数据结构 软件工程 设计模式 asp.net Java 数字图象处理 Sql 数据库
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

PHP演示最简单的MVC模式

Posted on 2008-10-01 11:17  analyzer  阅读(553)  评论(1编辑  收藏  举报

为了更好的演示MVC的工作方式,我们使用了一个简单的新闻文章发布系统作为例子.分为使用MVC和不使用MVC两种方式.
我们只作一个基本的演示,从数据库里读出一些文章列表,并在页面上显示。一般的流程就是,连接数据库,查询数据库,循环输出html结果。下面的代码就是如此做的。

 

Code
<?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:

 

Code
<?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:

 

Code
<?php
$articles = get_articles();
display_template(’articles
.tpl’);
?>

 

view:

 

Code
<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>

 

我要啦免费统计