想用MVC的方式寫一個小的CMS,建立了Controller、Model、View,但是不知道Controller向view傳值應該怎麼寫?
index.php
show();?>
testController.class.php
class testController{ function show(){ $testModel = new testModel(); $data = $testModel->get(); return $data; }}
testModel.class.php
require('database.php');get_connection();class testModel{ function get(){ $sql = "SELECT * FROM db_problem"; $res = mysql_query($sql); return $res; }}
testView.php
BUG列表
回複內容:
想用MVC的方式寫一個小的CMS,建立了Controller、Model、View,但是不知道Controller向view傳值應該怎麼寫?
index.php
show();?>
testController.class.php
class testController{ function show(){ $testModel = new testModel(); $data = $testModel->get(); return $data; }}
testModel.class.php
require('database.php');get_connection();class testModel{ function get(){ $sql = "SELECT * FROM db_problem"; $res = mysql_query($sql); return $res; }}
testView.php
BUG列表
首先你得在控制器裡指定模版比如 $this->display('test'); 然後在display方法中把模版include進來就行了
如果想複雜一點,給模版增加文法糖,就在display中判斷該模版是否有編譯過後的檔案,沒有的話則執行編譯(實質上就是正則替換,比如{$test}替換為$this->test),然後include編譯後的檔案
這樣就可以直接使用控制器的變數了
之前寫過一個簡單的mvc架構,你可以參考一下,核心內容在錢158行https://github.com/eyblog/mvc...
在controller裡面把模板中的變數和值存在資料裡面,file_get_content讀取view視圖檔案內容,模板變數標識可以按照你喜歡的來,比如{$user}或{{user}},然後Regex匹配替換,最後輸入echo
class Controller {
public $templateData = []; //儲存模板檔案的資料對應表
public function index(){
$this->assign($key,$value);
}
public function assign($key,$value){
$this->assign($key,$value);
}
public function display(){
/*載入view檔案內容 /*正則搜尋替換 /*輸出
}
}