博主信息
博文 39
粉丝 0
评论 0
访问量 41764
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
简单的MVC操作流程的案例--2019/08/06
LISTEN的博客
原创
955人浏览过

按照你的理解, 写一个简单的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();

运行实例 »

点击 "运行实例" 按钮查看在线实例


运行结果:

1.png

批改状态:合格

老师批语:还是自己写不出来呀, 全靠教学代码撑着了, 长此下去不行
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学