PHP之簡單實現(xiàn)MVC框架
1.概述
MVC全名是Model View Controller溉知,是模型(model)-視圖(view)-控制器(controller)的縮寫焚鹊,一種軟件設(shè)計典范,用一種業(yè)務(wù)邏輯衡瓶、數(shù)據(jù)徘公、界面顯示分離的方法組織代碼,將業(yè)務(wù)邏輯聚集到一個部件里面鞍陨,在改進(jìn)和個性化定制界面及用戶交互的同時步淹,不需要重新編寫業(yè)務(wù)邏輯。MVC被獨(dú)特的發(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ā)出指令第二步 控制器 -> 按指令選取一個合適的模型第三步 模型 -> 按控制器指令取相應(yīng)數(shù)據(jù)第四步 控制器 -> 按指令選取相應(yīng)視圖第五步 視圖 -> 把第三步取到的數(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ù)進(jìn)行組織,美化等,并最終向用戶終端輸出/ class testView{ function display($data){ echo $data; } }?>
運(yùn)行結(jié)果:
更多PHP相關(guān)技術(shù)請搜索千鋒PHP,做真實的自己寿烟,用良心做教育澈驼。
互聯(lián)網(wǎng)+時代,時刻要保持學(xué)習(xí)筛武,攜手千鋒PHP,Dream It Possible缝其。