1. 控制器將模型類得到的數據,傳遞給視圖進行顯示,因此視圖必須負責接收數據,另外重要的一點是當模型和視圖分開後,多個模型的數據能夠傳遞給一個視圖進行展現,也能夠說一個模型的數據在多個不一樣的視圖中進行展現。因此CodeIgniter 框架視圖的接口有兩個重要參數,php
public function view($view, $vars = array(), $return = FALSE)
$view 即便加載哪個視圖,$vars 便是傳入的數據, $return 即表示是直接輸出仍是返回(返回能夠用於調試輸出)html
2. 爲了達到很好的講述效果,咱們直接參看 CodeIgniter類中的 代碼數組
function view($view, $vars = array(), $return = FALSE) { return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_objects_to_array($vars), '_ci_return' => $return)); }
它用到兩個輔助函數,先看簡單的框架
/** * Object to Array * * Takes an object as input and converts the class variables to array key/vals * * @param object * @return array */ protected function _ci_object_to_array($object) { return (is_object($object)) ? get_object_vars($object) : $object; }
若是 $object 是對象的話,則經過 get_object_vars 函數返回關聯數組, 這個能夠做爲平時的小積累。函數
再看 _ci_load 函數測試
public function _ci_load($_ci_data) { // 經過 foreach 循環創建四個局部變量,且根據傳入的數組進行賦值(若是沒有,則爲FALSE) foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val) { $$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val]; } $file_exists = FALSE; // 設置路徑, 單純加載視圖的時候 ,_ci_path 爲空,會直接執行下面的 else 語句 if ($_ci_path != '') { $_ci_x = explode('/', $_ci_path); $_ci_file = end($_ci_x); } else { // 判斷 擴展名,若是沒有則加上.php 後綴 $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION); $_ci_file = ($_ci_ext == '') ? $_ci_view.'.php' : $_ci_view; // 搜索存放 view 文件的路徑 foreach ($this->_ci_view_paths as $view_file => $cascade) { if (file_exists($view_file.$_ci_file)) { $_ci_path = $view_file.$_ci_file; $file_exists = TRUE; break; } if ( ! $cascade) { break; } } } if ( ! $file_exists && ! file_exists($_ci_path)) { exit('Unable to load the requested file: '.$_ci_file); } include($_ci_path); }
這裏咱們針對最簡單的加載 view 的需求,抽取了完成基本 view 的代碼,從以上代碼能夠看到,加載 view 其實很簡單,include 便可。this
include 以前只是簡單對傳入的 視圖名做擴展名處理,以達到加載默認 .php 後綴的視圖時不須要包含.php ,而像 $this->load->view('test_view');spa
3. 咱們將使用 CodeIgniter 中視圖的例子調試
在views 下面新建一個文件
test_view.phpcode
<html> <head> <title>My First View</title> </head> <body> <h1>Welcome, we finally met by MVC, my name is Zhangzhenyu!</h1> </body> </html>
並在 controllers/welcome.php 中加載視圖
function saysomething($str) { $this->load->model('test_model'); $info = $this->test_model->get_test_data(); $this->load->view('test_view'); }
4. 測試
訪問 http://localhost/learn-ci/index.php/welcome/hello ,能夠看到以下輸出
Welcome, we finally met by MVC, my name is Zhangzhenyu!