PHP簡單的MVC框架實現(xiàn)方法
在PHP中使用MVC越來越流行了,特別是在一些開源的框架當中。
1.概述
MVC全名是Model View Controller,是模型(model)-視圖(view)-控制器(controller)的縮寫,一種軟件設計典范,用一種業(yè)務邏輯、數(shù)據(jù)、界面顯示分離的方法組織代碼,將業(yè)務邏輯聚集到一個部件里面,在改進和個性化定制界面及用戶交互的同時,不需要重新編寫業(yè)務邏輯。MVC被獨特的發(fā)展起來用于映射傳統(tǒng)的輸入、處理和輸出功能在一個邏輯的圖形化用戶界面的結(jié)構(gòu)中。
2.代碼結(jié)構(gòu)
3.代碼實現(xiàn)
<?php //function.php //控制器調(diào)用函數(shù) function C($name, $method){ require_once('libs/Controller/'.$name.'Controller.class.php'); //$testController = new testController(); //$testController->show(); eval('$obj = new '.$name.'Controller(); $obj->'.$method.'();'); } //模型調(diào)用函數(shù) function M($name){ require_once('libs/Model/'.$name.'Model.class.php'); eval('$obj = new '.$name.'Model();'); return $obj; } //視圖調(diào)用函數(shù) function V($name){ require_once('libs/View/'.$name.'View.class.php'); eval('$obj = new '.$name.'View();'); return $obj; } //過濾非法值 function daddslashes($str){ return (!get_magic_quotes_gpc())?addslashes($str):$str; } ?> <?php //test.php /* 第一步 瀏覽者 -> 調(diào)用控制器,對它發(fā)出指令 第二步 控制器 -> 按指令選取一個合適的模型 第三步 模型 -> 按控制器指令取相應數(shù)據(jù) 第四步 控制器 -> 按指令選取相應視圖 第五步 視圖 -> 把第三步取到的數(shù)據(jù)按用戶想要的樣子顯示出來 */ require_once('View/testView.class.php'); require_once('Model/testModel.class.php'); require_once('Controller/testController.class.php'); $testController = new testController(); $testController->show(); ?> <?php //testController.class.php /* 控制器的作用是調(diào)用模型,并調(diào)用視圖,將模型產(chǎn)生的數(shù)據(jù)傳遞給視圖,并讓相關(guān)視圖去顯示 */ class testController{ function show(){ /*$testModel = new testModel(); $data = $testModel->get(); $testView = new testView(); $testView->display($data);*/ $testModel = M('test'); $data = $testModel->get(); $testView = V('test'); $testView->display($data); } } ?> <?php //testModel.class.php /* 模型的作用是獲取數(shù)據(jù)并處理,返回數(shù)據(jù) */ class testModel{ function get(){ return "hello world"; } } ?> <?php //testView.class.php /* 視圖的作用是將獲得的數(shù)據(jù)進行組織,美化等,并最終向用戶終端輸出 */ class testView{ function display($data){ echo $data; } } ?>
運行結(jié)果:
PHP中的MVC
MVC[1]在軟件工程中是一種軟件的架構(gòu)。從php的角度來講MVC有一些不同。
Model(模型),程序應用功能的實現(xiàn),程序的邏輯的實現(xiàn)。在PHP中負責數(shù)據(jù)管理,數(shù)據(jù)生成。
View(視圖),圖形界面邏輯。在PHP中負責輸出,處理如何調(diào)用模板、需要的資源文件。
Controller(控制器),負責轉(zhuǎn)發(fā)請求,對請求處理。在PHP中根據(jù)請求決定調(diào)用的視圖及使用的數(shù)據(jù)。
為什么使用MVC
MVC的主要作用是為了將代碼分層、分類。
MVC的主要目的是為了解決Web開發(fā)中分離開發(fā)與設計工作,使其工作相對獨立。
在這樣的過程中還發(fā)現(xiàn)了其他的一些優(yōu)點,網(wǎng)站的目錄結(jié)構(gòu)更加清晰,網(wǎng)站更易維護與擴展,可以實現(xiàn)模塊的復用。
相關(guān)文章
老生常談PHP數(shù)組函數(shù)array_merge(必看篇)
下面就為大家?guī)硪黄仙U凱HP數(shù)組函數(shù)array_merge(必看篇)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05TP3.2.3框架使用CKeditor編輯器在頁面中上傳圖片的方法分析
這篇文章主要介紹了TP3.2.3框架使用CKeditor編輯器在頁面中上傳圖片的方法,結(jié)合實例形式分析了thinkPHP3.2.3框架使用CKeditor編輯器相關(guān)配置方法與操作注意事項,需要的朋友可以參考下2019-12-12