2.MVC简单实现

  • 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感觉思想很重要。思想指导一切。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值