举例:把数据库中的数据查询出来(通常是二维关联数组),并在页面中以表格的形式展示。
Model.php(模型文件)
<?php
class Model{
public static function getData(){
$data=[
['id'=>101,'name'=>'Peter','age'=>28,'salary'=>3000],
['id'=>102,'name'=>'Jack','age'=>24,'salary'=>3500],
['id'=>103,'name'=>'Tom','age'=>22,'salary'=>3900],
['id'=>104,'name'=>'Bill','age'=>21,'salary'=>6900],
];
return $data;
}
}
?>
View.php(视图文件)
<?php
class View{
public static function display($data){
$table = '<h3 align="center">用户信息表</h3>';
$table .= '<table border="1" cellspacing="0" cellspacing="0" width="50%" align="center">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>salary</th>
</tr>';
foreach ($data as $value){
$table .= '<tr>';
$table .= '<td>'.$value['id'].'</td>';
$table .= '<td>'.$value['name'].'</td>';
$table .= '<td>'.$value['age'].'</td>';
$table .= '<td>'.$value['salary'].'</td>';
$table .= '</tr>';
}
$table .= '</table>';
return $table;
}
}
?>
Controller.php(控制器文件)
<?php
class Controller{
public function show(){
//从模型中获取数据
$data=Model::getData();
//展示数据
echo View::display($data);
}
}
?>
index.php(入口文件)
<?php
//引入我们的mvc类
require_once("Model.php");//导入模型类
require_once("View.php");//导入视图类
require_once("Controller.php");//导入控制器
//调用指定控制器中的指定方法,使应用运行起来
$c=isset($_GET['c'])?$_GET['c']:'Controller';
$a=isset($_GET['a'])?$_GET['a']:'show';
$controller = new $c;
$controller->$a();
?>
MVC应用程序被分为三个核心部件:模型(M),视图(V),控制器(C),它们各自处理各自的任务.MVC中,真正干活的是控制器中的操作方法,它是URL的路由目标。