mvc原理:
M->Model模型, 负责数据访问.
C->Controller控制器, 负责解析HTTP请求并转发和与模型与视图进行交互.
V-View: 负责生成HTML页面.
MVC流程:
view发出http请求被controller拦截、接受,controller进行分析处理,从model中取出数据,形成一个view,返回给前端。
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; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
model 实例
<?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'], ]; } }
运行实例 »
点击 "运行实例" 按钮查看在线实例
controller 实例
<?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( );
运行实例 »
点击 "运行实例" 按钮查看在线实例
解决对象之间高度耦合的方法:
(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();
运行实例 »
点击 "运行实例" 按钮查看在线实例