批改狀態(tài):合格
老師批語:寫得可以
MVC的全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,是一種軟件設(shè)計(jì)典范。它是用一種業(yè)務(wù)邏輯、數(shù)據(jù)與界面顯示分離的方法來組織代碼.
使用的MVC的目的:在于將M和V的實(shí)現(xiàn)代碼分離,從而使同一個(gè)程序可以使用不同的表現(xiàn)形式。比如Windows系統(tǒng)資源管理器文件夾內(nèi)容的顯示方式,下面兩張圖中左邊為詳細(xì)信息顯示方式,右邊為中等圖標(biāo)顯示方式,文件的內(nèi)容并沒有改變,改變的是顯示的方式。不管用戶使用何種類型的顯示方式,文件的內(nèi)容并沒有改變,達(dá)到M和V分離的目的。
<?php // 模型類: 用于數(shù)據(jù)庫操作,數(shù)據(jù)訪問 class Model { protected $pdo; public function __construct() { $this->pdo=new \PDO('mysql:host=127.0.0.1;dbname=php','root','root'); } public function getData() { $sql='select * from `stud`'; $stmt=$this->pdo->prepare($sql); $stmt->execute(); $res=$stmt->fetchAll(\PDO::FETCH_ASSOC); return $res; } } $obj=new Model(); $obj->getData();
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
<?php // 視圖類: 渲染數(shù)據(jù) class View { public function fetch($data) { $table = '<table border="1" cellspacing="0" align="center" cellpadding="3" width="600" >'; $table .= '<caption>演員信息列表</caption>'; $table.=' <thead><tr bgcolor="#add8e6"><th>I D</th><th>姓名</th><th>年齡</th><th>性別</th><th>手機(jī)</th></tr></thead>'; $table.= '<tbody >'; foreach ($data as $stud){ $table.='<tr>'; $table.='<td>'.$stud['stud_id'].'</td>'; $table.='<td>'.$stud['name'].'</td>'; $table.='<td>'.$stud['age'].'</td>'; $table.='<td>'.$stud['sex'].'</td>'; $table.='<td>'.$stud['mobile'].'</td>'; $table.='</tr>'; } $table.='</tbody></table>'; return $table; } }
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
<?php // 控制器2: 依賴注入, 解決了對(duì)象之間的高度耦合的問題 // 加載模型類 require 'Model.php'; // 加載視圖類 require 'View.php'; // 控制器類 class Controller { // 注入點(diǎn)是一個(gè)普通方法 public function index(Model $model,View $view) { // 1獲取數(shù)據(jù) $data=$model->getData(); // 2渲染模板 return $view->fetch($data); } } // 客戶端調(diào)用 $controller=new Controller(); $model=new Model(); $view=new View(); echo $controller->index($model,$view);
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
原來數(shù)據(jù)庫中的列表:
在控制器,前端顯示的列表:
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)