批改状态:不合格
老师批语:请看清作业要求, 必须基于真实的数据表查询 , 不允许用数组替代
mvc原理:
M->Model模型, 负责数据访问.
C->Controller控制器, 负责解析HTTP请求并转发和与模型与视图进行交互.
V-View: 负责生成HTML页面.
MVC流程:
view发出http请求被controller拦截、接受,controller进行分析处理,从model中取出数据,形成一个view,返回给前端。
<?php
class view
{
public function fetch($data){
$table ='<table border =" 1 " cellspacing = "0" cellpadding = "3" width = "400">';
// $table ='<caption>信息表</caption>';
// $table = '<tr bgcolor ="#add8e6"><th>ID</th><th>姓名</th><th国籍</th></tr>';
foreach ($data as $list){
$table .= '<tr>';
$table .= '<td>' . $list['id'] . '</td>';
$table .= '<td>' . $list['name'] . '</td>';
$table .= '<td>' . $list['model'] . '</td>';
$table .= '</tr>';
}
$table .= '</table>';
return $table;
}
}点击 "运行实例" 按钮查看在线实例
<?php
class model
{
public function getData(){
return[
[ 'id' => 1,'name' =>'Newton','model' => 'UK'],
[ 'id' => 2,'name' =>'Aristotle','model' => 'Greek'],
[ 'id' => 3,'name' =>'Galilei','model' => 'Italia'],
];
}
}点击 "运行实例" 按钮查看在线实例
<?php
require 'model.php';
require 'view.php';
class Controller
{
public function index( ){
$model = new model();
$data = $model->getData();
$view = new view();
return $veiw->fetch($data);
}
}
$Controller = new Controller();
echo $Controller->index( );点击 "运行实例" 按钮查看在线实例
![1565106346366169.png EBCGG[K7(F$R%]47F4TS`YI.png](https://img.php.cn/upload/image/958/264/740/1565106346366169.png)
解决对象之间高度耦合的方法:
(1)普通方法中实现了依赖注入 注入点是一个普通方法
<?php
require 'model.php';
require 'view.php';
class Controller
{
public function index( model $model, view $view){
// $model = new model();
$data = $model->getData();
// $view = new view();
return $view->fetch($data);
}
}
$Controller = new Controller();
$model = new model();
$veiw = new view();
echo $Controller->index( $model, $veiw);点击 "运行实例" 按钮查看在线实例
(2)注入点是一个构造方法
<?php
require 'model.php';
require 'view.php';
class Controller{
protected $model;
protected $view;
public function __construct(model $model,view $view)
{
$this->model=$model;
$this->view=$view;
}
public function index(){
$data = $this->model->getData();
return $this->view->fetch($data);
}
}
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
echo $controller->index();点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号