MVC 模式是現代 Web 開發的基石,但很多教程只講理論不落地。本文通過一個極簡留言本(僅 6 個文件),完整演示從入口分發到模型/視圖/控制器分層協作的全流程,讓你在代碼層面真正理解 MVC 運作機制。
├── index.php # 單一入口
├── post.htm # 留言表單
└── lib/
├── DataAccess.php # 資料庫訪問層
├── Model.php # 業務邏輯層
├── View.php # 視圖渲染層
└── Controller.php # 請求分發層
僅封裝連線、查詢、獲取行三個核心方法,採用 mysql_pconnect 長連線:
class DataAccess {
var $db, $query;
function __construct($host,$user,$pass,$db) {
$this->db = mysql_pconnect($host,$user,$pass);
mysql_select_db($db,$this->db);
}
function fetch($sql) { $this->query = mysql_unbuffered_query($sql,$this->db); }
function getRow() { return mysql_fetch_array($this->query, MYSQL_ASSOC) ?: false; }
}
所有資料操作(增刪改查)集中於此,控制器零 SQL:
class Model {
var $dao;
function __construct(&$dao) { $this->dao = $dao; }
function listNote() { $this->dao->fetch("SELECT * FROM note"); }
function postNote($name,$content) { /* INSERT SQL */ }
function deleteNote($id) { /* DELETE SQL */ }
function getNote() { return $this->dao->getRow(); }
}
採用「基類 + 子類」模式,根據 $_GET['action'] 實例化對應子控制器:
class Controller {
var $model, $view;
function __construct(&$dao) { $this->model = new Model($dao); }
function getView() { return $this->view; }
}
class listController extends Controller {
function __construct(&$dao) {
parent::__construct($dao);
$this->view = new listView($this->model);
}
}
// postController、deleteController 結構同理
$dao = new DataAccess('localhost','root','','test');
$action = $_GET["action"] ?? 'list';
switch ($action) {
case 'post': $controller = new postController($dao,$_POST); break;
case 'delete': $controller = new deleteController($dao,$_GET["id"]); break;
default: $controller = new listController($dao);
}
$controller->getView()->display();
各子類負責具體 HTML 組裝,從 Model 獲取數據:
class listView extends View {
function __construct(&$model) {
parent::__construct($model);
$this->model->listNote();
while ($note = $this->model->getNote()) {
$this->output .= "姓名:$note[name] 留言:$note[content] 刪除 ";
}
}
}
index.php?action=listDataAccess → listController → listViewlistView 調用 Model::listNote() 觸發 SQL 查詢Model 通過 DataAccess 獲取資料集View 遍歷結果組裝 HTML → display() 輸出這個「簡陋」的留言本,卻完整包含了 MVC 的靈魂。建議動手跑通、改造、擴展它——這比閱讀十本理論書更有效。