批改状态:合格
老师批语:写得可以
MVC的全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范。它是用一种业务逻辑、数据与界面显示分离的方法来组织代码.
使用的MVC的目的:在于将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。比如Windows系统资源管理器文件夹内容的显示方式,下面两张图中左边为详细信息显示方式,右边为中等图标显示方式,文件的内容并没有改变,改变的是显示的方式。不管用户使用何种类型的显示方式,文件的内容并没有改变,达到M和V分离的目的。

<?php
// 模型类: 用于数据库操作,数据访问
class Model
{
protected $pdo;
public function __construct()
{
$this->pdo=new \PDO('mysql:host=127.0.0.1;dbname=php','root','root');
}
public function getData()
{
$sql='select * from `stud`';
$stmt=$this->pdo->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll(\PDO::FETCH_ASSOC);
return $res;
}
}
$obj=new Model();
$obj->getData();点击 "运行实例" 按钮查看在线实例
<?php
// 视图类: 渲染数据
class View
{
public function fetch($data)
{
$table = '<table border="1" cellspacing="0" align="center" cellpadding="3" width="600" >';
$table .= '<caption>演员信息列表</caption>';
$table.=' <thead><tr bgcolor="#add8e6"><th>I D</th><th>姓名</th><th>年龄</th><th>性别</th><th>手机</th></tr></thead>';
$table.= '<tbody >';
foreach ($data as $stud){
$table.='<tr>';
$table.='<td>'.$stud['stud_id'].'</td>';
$table.='<td>'.$stud['name'].'</td>';
$table.='<td>'.$stud['age'].'</td>';
$table.='<td>'.$stud['sex'].'</td>';
$table.='<td>'.$stud['mobile'].'</td>';
$table.='</tr>';
}
$table.='</tbody></table>';
return $table;
}
}点击 "运行实例" 按钮查看在线实例
<?php
// 控制器2: 依赖注入, 解决了对象之间的高度耦合的问题
// 加载模型类
require 'Model.php';
// 加载视图类
require 'View.php';
// 控制器类
class Controller
{
// 注入点是一个普通方法
public function index(Model $model,View $view)
{
// 1获取数据
$data=$model->getData();
// 2渲染模板
return $view->fetch($data);
}
}
// 客户端调用
$controller=new Controller();
$model=new Model();
$view=new View();
echo $controller->index($model,$view);点击 "运行实例" 按钮查看在线实例
原来数据库中的列表:

在控制器,前端显示的列表:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号