To better demonstrate the way MVC works, we use a simple news article publishing system as an example. There are two methods: MVC and MVC. We will only give a basic demonstration, read some article lists from the database, and display them on the page. The general process is to connect to the database, query the database, and output html results cyclically. The following code does this.
<?php mysql_connect(…); $result = mysql_query('select * from news order by article_date desc'); ?>
The MVC method is as follows.
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:
Writing PHP Code directly to HTML files does not feel very professional or secure. Other problems may occur when using MVC, such as template parsing and route forwarding. Here is a simple demonstration of the MVC process.