Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
实现效果
自定义控制器和方法
<?php
//配偶文件
//数据库配置信息
const DATABASE = [
'type' => 'mysql',
'dbname' => 'phpedu',
'username' => 'root',
'password' => 'root'
];
//根目录
const ROOT_PATH = __DIR__;
//应用相关
const APP = [
//默认控制器
'default_controller' => 'index',
//控制器默认使用的方法
'default_action' => 'index',
];
<?php
//核心类库
namespace phpcn;
use PDO;
class Model
{
//创建链接对象
protected $db;
//Model对象实例化时,链接数据库
public function __construct($dsn, $username, $password)
{
$this->db = new PDO($dsn, $username, $password);
}
//公共方法供用户进行数据库的操作
public function getAll($n = 5)
{
$stmt = $this->db->prepare("SELECT * FROM `staff` LIMIT $n");
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
<?php
//核心类库
namespace phpcn;
class View
{
//视图类实现模板的赋值和模板的渲染
public function display($staffs)
{
include ROOT_PATH . '/view/' . 'show.php';
}
}
<!DOCTYPE html>
<html lang="en">
<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>
<caption>员工信息表</caption>
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>性别</th>
<th>邮箱</th>
</tr>
</thead>
<tbody>
<?php foreach ($staffs as $staff) : ?>
<?php extract($staff) ?>
<tr>
<td><?= $id ?></td>
<td><?= $name ?> </td>
<td><?= $gender ? "男" : "女" ?> </td>
<td><?= $email ?> </td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</body>
</html>
<?php
//核心类库
namespace phpcn;
class Controller
{
//模型对象
protected $model;
//视图对象
protected $view;
//控制器实例化时要确保模型与对象可用
public function __construct($model, $view)
{
$this->model = $model;
$this->view = $view;
}
public function index($n = 5)
{
//通过模型中的公共方法获取数据
$staffs = $this->model->getAll($n);
//将数据赋值到模板中,通过视图类渲染模板
$this->view->display($staffs);
}
}
<?php
namespace phpcn;
class UserController extends Controller
{
public function user()
{
echo '<h2>Hello PHPcn</h2>';
}
}
<?php
//入口文件
namespace phpcn;
//加载配置项
require __DIR__ . '/config.php';
//加载核心类库
require ROOT_PATH . '/core/Model.php';
require ROOT_PATH . '/core/View.php';
require ROOT_PATH . '/core/Controller.php';
//加载自定义模型
require ROOT_PATH . '/model/StaffModel.php';
//结构数据库参数数组
extract(DATABASE);
//实例化模型类
$dsn = sprintf('%s:dbname=%s', $type, $dbname);
$model = new StaffModel($dsn, $username, $password);
//实例化视图类
$view = new View(null, null);
//获取自定义控制器和自定义方法
$c = $_GET['c'] ?? APP['default_controller'];
$a = $_GET['a'] ?? APP['default_action'];
//获取定义控制器名
$class = ucfirst($c) . 'Controller';
//加载自定义控制器
require ROOT_PATH . '/Controller/' . $class . '.php';
//完整控制器类名
$fullclass = __NAMESPACE__ . '\\' . $class;
$controller = new $fullclass($model, $view);
$controller->$a(10);
//执行自定义控制器和方法
//index.php?c=user&a=user