批改状态:合格
老师批语:还是自己写不出来呀, 全靠教学代码撑着了, 长此下去不行
按照你的理解, 写一个简单的MVC操作流程的案例, 要求:
1. 使用真实的数据表中的数据;
2. 要求在构造方法中实现模型与视图的对象依赖注入
1、Model.php
<?php
// 模型类: 用于数据库操作,数据访问
class Model
{
protected $pdo;
public function __construct()
{
$this->pdo=new \PDO('mysql:host=localhost;dbname=listen0724','root','root');
}
public function getData()
{
$sql='select `detail_id`,`name`,concat(left(`detail`,30),\'...\') as `detail` from `details`';
$stmt=$this->pdo->prepare($sql);
$stmt->execute();
$res=$stmt->fetchAll(\PDO::FETCH_ASSOC);
return $res;
}
}点击 "运行实例" 按钮查看在线实例
2、View.php
<?php
// 视图类: 渲染数据
class View
{
public function fetch($data)
{
$table = '<table border="1" cellspacing="0" align="center" cellpadding="3" width="800" style="text-align: center">';
$table .= '<caption>信息列表</caption>';
$table.=' <thead><tr bgcolor="#00F7DE"><th>序号</th><th>名称</th><th>详情</th></tr></thead>';
$table.= '<tbody >';
foreach ($data as $detail){
$table.='<tr>';
$table.='<td>'.$detail['detail_id'].'</td>';
$table.='<td>'.$detail['name'].'</td>';
$table.='<td>'.$detail['detail'].'</td>';
$table.='</tr>';
}
$table.='</tbody></table>';
return $table;
}
}点击 "运行实例" 按钮查看在线实例
3、Controller.php
<?php
// 控制器2: 依赖注入
// 加载模型类
require 'Model.php';
// 加载视图类
require 'View.php';
// 控制器类
class Controller
{
protected $model;
protected $view;
// 注入点是一个构造方法
public function __construct(Model $model,View $view)
{
$this->model=$model;
$this->view=$view;
}
public function index()
{
// 1获取数据
$data=$this->model->getData();
// 2渲染模板
return $this->view->fetch($data);
}
}
// 客户端调用
$model=new Model();
$view=new View();
$controller=new Controller($model,$view);
echo $controller->index();点击 "运行实例" 按钮查看在线实例
运行结果:

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