批改状态:未批改
老师批语:
MVC是最经典,也是最流行的Web项目设计思想
M:Model模型层,用来实现也数据库相关的操作
V:View视图层,用来实现用户界面与数据展示
C:Controller 控制器层,根据视图层的要求选择合适的模型
效果图

文件路径

下边看代码
controller文件夹里的代码
这个文件是通俗的理解就是将下边两个文件里的代码引入执行操作
<?php
/**
* User: Z先生
* Date: 2018/5/10
*/
namespace mvc\controller;
class Controller
{
public function get(){
require './model/Model.php';
$a = new \mvc\model\Model('php','root','root');
$aa =$a->select('aaa');
$aaa = $a->result;
require './view/View.php';
$b = new \mvc\view\View($aaa);
$bb = $b->getData();
$b->display($bb);
}
}点击 "运行实例" 按钮查看在线实例
model文件夹
这个文件执行的是数据库操作,或者数据收集,index文件是测试
<?php
/**
* User: Z先生
* Date: 2018/5/10
*/
namespace mvc\model;
class Model
{
public $pdo = null;
public $result = [];
public function __construct($dbname,$user,$pass)
{
//数据库连接
$this->pdo = new \PDO('mysql:host=127.0.0.1;dbname='.$dbname,$user,$pass);
}
//执行查询,获取结果集
public function select($table)
{
//创建预处理语句
$stmt = $this->pdo->prepare("SELECT * FROM {$table} ;");
//执行查询
$stmt -> execute();
//解析结果集:将复制过来的 $result 替换成成 $this->result
$this->result = $stmt -> fetchAll(\PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
<?php
/**
* User: Z先生
* Date: 2018/5/10
* 测试Model
*/
require 'Model.php';
use mvc\model\Model;
$a = new Model('php','root','root');
$a->select('aaa');
print_r($a->result);点击 "运行实例" 按钮查看在线实例
view文件夹
这个文件夹操作的是数据处理,就是把后台处理好的数据,在这里弄成展示模板
<?php
/**
* User: Z先生
* Date: 2018/5/10
*/
namespace mvc\view;
class View
{
public $data =null;
public function __construct($data)
{
$this->data = $data;
}
public function getData()
{
return $this->data;
}
public function display($da)
{
$table = '
<style type="text/css">
table,th,td {
border:1px solid black;
}
table {
border-collapse: collapse;
width: 60%;
margin: 30px auto;
text-align: center;
}
table tr:first-child {
background-color: lightgreen;
}
table caption {
font-size:1.5em;
margin-bottom: 15px;
}
</style>
<table>
<caption>员工信息表</caption>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>工资</th>
</tr>';
foreach ($da as $staff) {
$table .= '<tr>';
$table .= '<td>'.$staff['id'].'</td>';
$table .= '<td>'.$staff['name'].'</td>';
$table .= '<td>'.$staff['age'].'</td>';
$table .= '<td>'.$staff['money'].'</td>';
}
$table .= '</table>';
echo $table;
}
}点击 "运行实例" 按钮查看在线实例
<?php
/**
* User: Z先生
* Date: 2018/5/10
*/
require '../model/Model.php';
use mvc\model\Model;
$a = new mvc\model\Model('php','root','root');
$aa =$a->select('aaa');
$aaa = $a->result;
require '../view/View.php';
use mvc\model\View;
$b = new mvc\view\View($aaa);
$bb = $b->getData();
$b->display($bb);点击 "运行实例" 按钮查看在线实例
/************************************************************************************/
最后一个index文件就是执行操作controller的了
<?php /** * User: Z先生 * Date: 2018/5/10 */ require 'controller/Controller.php'; use mvc\controller; $a = new \mvc\controller\Controller(); $a->get();
点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号