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!