一、core
- Model.php
- View.php
- Controller.php
<?php
namespace phpedu;
use PDO;
class Model{
protected $db;
// 控制LIMIT参数
protected $n;
public function __construct($dsn,$username,$password,$n=10){
$this->db = new PDO($dsn,$username,$password);
$this->n = $n;
}
// 获取数据库数据并返回
public function getAll(){
$stmt = $this->db->prepare('SELECT * FROM `staff` LIMIT ?');
$stmt -> bindParam(1,$this->n,PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchALL();
}
}
<?php
namespace phpedu;
class View{
public function display($data){
// 把数据赋给模板变量
$staffs=$data;
//引入模板
require ROOT_PATH . '\\' . 'view\show.php';
}
}
<?php
namespace phpedu;
// 控制器类似于中间人代理model以及view
class Controller{
protected $model;
protected $view;
// 初始化模型和视图对象
public function __construct($model, $view){
$this->model = $model;
$this->view = $view;
}
// 页面渲染
public function index(){
$data = $this->model->getAll();
$this->view->display($data);
}
}
二、Model、View、Controller
<?php
namespace phpedu;
//自定义模板类
class StaffModel extends Model{
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>员工管理系统</title>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="5" width="400">
<caption style="font-size: 1.2em;">员工信息表</caption>
<thead bgcolor="lightcyan">
<tr>
<th>id</th>
<th>姓名</th>
<th>性别</th>
<th>邮箱</th>
<th>操作</th>
</tr>
</thead>
<tbody align="center">
<?php foreach ($staffs as [$id, $name, $sex, $email]) : ?>
<tr>
<td><?= $id ?></td>
<td><?= $name ?></td>
<td><?= $sex ? '女' : '男' ?></td>
<td><?= $email ?></td>
<td>
<a href="">编辑</a>
<a href="">删除</a>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</body>
</html>
<?php
namespace phpedu;
// 自定义控制器
class IndexController extends Controller{
}
三、配置,入口文件:config.php、index.php
<?php
// 数据库连接参数
define('DATABASE', [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'phpedu',
'port' => '3306',
'charset' => 'utf8',
'username' => 'root',
'password' => 'root'
]);
// 应用相关
define('APP', [
// 默认控制器
'default_controller' => 'index',
// 默认方法
'default_action' => 'index'
]);
// 项目根路径
define('ROOT_PATH', __DIR__);
<?php
namespace phpedu;
// 加载配置项
require __DIR__ . '/config.php';
// 加载框架的核心类
require __DIR__ . '/core/Model.php';
require __DIR__ . '/core/View.php';
require __DIR__ . '/core/Controller.php';
// 加载自定义模型
require __DIR__ . '/model/StaffModel.php';
// 获取方法及控制器参数
$c = $_GET['c'] ?? APP['default_controller'];
$a = $_GET['a'] ?? APP['default_action'];
$class = ucfirst($c) . 'Controller';
require __DIR__ . '/controller/' . $class . '.php';
// 获取模型对象
extract(DATABASE);
$dsn = sprintf("%s:dbname=%s", $type, $dbname);
$model = new StaffModel($dsn, $username, $password, 5);
// 获取视图对象
$view = new View();
// 获取控制器对象
$realclass = __NAMESPACE__ . '\\' . $class;
$controller = new $realclass($model, $view);
echo $controller->$a();