- MVC
- StudentModel.php
- StudentController.php
- student.html
- index.php
MVC中M(modle)表示数据处理,V(View)表示视图,C(Contorller)表示控制器,
用户发起请求,数据将传递给控制器,控制器调用模型进行数据处理,模型将处理过的数据返回给控制器,控制器调用视图呈现数据,最终视图呈现出html给用户
千遍万遍不如手写一遍
StudentModel.php
<?php
Class StudentModel
{
protected $link;
#实例化对象时,直接连接数据库
public function __construct()
{
$this->link = new MySqli('localhost','root','root','mytp');
$this->link->set_charset('utf8');
}
#获取数据库中的数据
public function getAll()
{
$sql = 'Select * from `student`';
$res = $this->link->query($sql);
return $res->fetch_all(MYSQLI_ASSOC);
}
}
StudentController
class StudentController
{
#控制器index方法,调用数据,传给视图并呈现界面
public function index()
{
require 'StudentModel.php';
#获取模型数据
$model = new StudentModel();
$data = $model->getAll();
#将模型数据传递给视图
require 'student.html';
}
}
student.html
<html>
<body>
<table><tr><th>ID</th><th>姓名</th><th>性别</th></tr>
<?php foreach ($data as $row): ?>
<tr><th><?=row['id']?></th>
<th><?=row['name']></th>
<th><?=['男','女'][$row['gender']]</th>
<tr>
<?php endforeach;?>
</table>
</body>
</html>
index.php
require 'StudentController.php';
$a = new StudentController();
$a->index();
写完下来,感觉就是功能模块化,要什么调用什么,反过来看thinkphp感觉思想很重要。思想指导一切。