MVC的工作原理以及目標(biāo)就是將用戶(hù)請(qǐng)求的URL映射到“控制器中的方法上”
MVC 是一種使用 MVC(Model View Controller 模型-視圖-控制器)設(shè)計(jì)創(chuàng)建 Web 應(yīng)用程序的模式:
Model(模型)表示應(yīng)用程序核心(比如數(shù)據(jù)庫(kù)記錄列表)
View(視圖)顯示數(shù)據(jù)(數(shù)據(jù)庫(kù)記錄)
Controller(控制器)處理輸入(寫(xiě)入數(shù)據(jù)庫(kù)記錄)
Model(模型)是應(yīng)用程序中用于處理應(yīng)用程序數(shù)據(jù)邏輯的部分,通常模型對(duì)象負(fù)責(zé)在數(shù)據(jù)庫(kù)中存取數(shù)據(jù)。
View(視圖)是應(yīng)用程序中處理數(shù)據(jù)顯示的部分,通常視圖是依據(jù)模型數(shù)據(jù)創(chuàng)建的。
Controller(控制器)是應(yīng)用程序中處理用戶(hù)交互的部分,通常控制器負(fù)責(zé)從視圖讀取數(shù)據(jù),控制用戶(hù)輸入,并向模型發(fā)送數(shù)據(jù)。
接下來(lái)通過(guò)代碼來(lái)展示MVC框架的原理:
如圖創(chuàng)建項(xiàng)目,首先創(chuàng)建 模型 文件也就是數(shù)據(jù):Model.php
// M Model 數(shù)據(jù),用模型 用二維數(shù)組模擬數(shù)據(jù) $data = [ ['id'=>1,'name'=>'老王','age'=>22,'email'=>'wang@qq.com'], ['id'=>2,'name'=>'老王','age'=>22,'email'=>'wang@qq.com'], ['id'=>3,'name'=>'老王','age'=>22,'email'=>'wang@qq.com'], ['id'=>4,'name'=>'老王','age'=>22,'email'=>'wang@qq.com'], ['id'=>5,'name'=>'老王','age'=>22,'email'=>'wang@qq.com'] ];
接下來(lái)創(chuàng)建 視圖模板 文件 顯示數(shù)據(jù):show.html
<table> <tr> <th>ID</th> <th>姓名</th> <th>年齡</th> <th>郵箱</th> </tr> <?php foreach($data as $staff): ?> <tr> <td><?=$staff['id']; ?></td> <td><?=$staff['name']; ?></td> <td><?=$staff['age']; ?></td> <td><?=$staff['email']; ?></td> </tr> <?php endforeach; ?> </table>
接下來(lái)創(chuàng)建 控制器文件,方法內(nèi)指定模板文件以及顯示的數(shù)據(jù):Staff.php
<?php class Staff { public function show($data){ // 引入模板 include __DIR__.'/../view/show.html'; } }
最后一步創(chuàng)建這個(gè)小MVC項(xiàng)目的入口文件:index.php
<?php // 1、將用戶(hù)請(qǐng)求的控制器和操作從URL地址中取出 $url = explode('/',$_SERVER['REQUEST_URI']); $controller = ucfirst($url[3]); $action = $url[4]; // 2、加載控制器類(lèi)和模型類(lèi)文件 require_once __DIR__.'/controller/'.$controller.'.php'; require_once __DIR__.'/model/Model.php'; // 3、調(diào)用控制器中的方法 echo (new $controller)->$action($data);
此時(shí)MVC文件以及入口文件創(chuàng)建完畢,通過(guò)本地虛擬主機(jī)創(chuàng)建的域名和MVC項(xiàng)目進(jìn)行綁定,例如域名為 mvc.io
在瀏覽器的地址欄中輸入:mvc.io/index.php/staff/show 當(dāng)頁(yè)面中出現(xiàn)以下界面則證明MVC項(xiàng)目創(chuàng)建成功
微信掃碼
關(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)