在php中Controller向View傳值

來源:互聯網
上載者:User
想用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列表
  
ID 問題 提交時間

回複內容:

想用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列表
  
ID 問題 提交時間

首先你得在控制器裡指定模版比如 $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檔案內容   /*正則搜尋替換   /*輸出

}
}

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.