模型类:model.php
<?php
class Model
{
public function getData()
{
require $_SERVER['DOCUMENT_ROOT'].'/config/connect.php';
$sql="SELECT * FROM `user` LIMIT 10";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$user = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $user;
// print_r($users);
}
}
?>
<html>
<head>
<body>
<style>
table {border-collapse: collapse; border: 1px solid;text-align: center; width: 500px;height: 150px;width: 600px;}
caption {font-size: 1.2rem; margin-bottom: 10px;}
tr:first-of-type { background-color:wheat;}
td,th {border: 1px solid; padding:5px}
</style>
</body>
</head>
</html>
视图类:View.php
<?php
class View
{
public function fetch($data)
{
$table='<table>';
$table.='<caption>用户列表</caption>';
$table.='<tr><th>id</th><th>账户</th><th>姓名</th><th>tel</th><th>存款</th></tr>';
foreach($data as $user) {
$table .= '<tr>';
$table .= '<td>' . $user['id'] . '</td>';
$table .= '<td>' . $user['account'] . '</td>';
$table .= '<td>' . $user['username'] . '</td>';
$table .= '<td>' . $user['phone'] . '</td>';
$table .= '<td>' . $user['money'] . '</td>';
$table .= '</tr>';
}
$table.='</table>';
return $table;
}
}
控制器一,demo.php
<?php
require 'Model.php';
require 'View.php';
//创建控制 方法一:
class controller
{
public function index()
{
$m=new Model;
//print_r($m->getData());
$data=$m->getData();
$v=new View;
$res=$v->fetch($data);
return $res;
}
}
$controller=new controller;
echo $controller->index();
控制方法二,demo1.php
<?php
require 'model.php';
require 'view.php';
//创建控制 方法二:
class controller1
{
public function index($m,$v){
//获取数据
$data=$m->getData();
//渲染视图
return $v->fetch($data);
}
}
$m=new Model;
$v=new View;
$controller1=new controller1;
$res=$controller1->index($m,$v);
echo $res;
控制方法三,demo2.php
<?php
require 'model.php';
require 'view.php';
class controller2
{
//依赖对象属性
private $m;
private $v;
public function __construct(Model $m, View $v)
{
$this->m = $m;
$this->v = $v;
}
public function index()
{
$data = $this->m->getData();
return $this->v->fetch($data);
}
}
$m = new Model;
$v = new View;
$controller2 = new controller2($m,$v);
echo $controller2->index();
总结:MVC基本认识大概思路有了。还需要认真多抄几遍估计可以加深下认识。