为了更好的演示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:
立即学习“PHP免费学习笔记(深入)”;
<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的一个过程。
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号