您的位置:首页 > 其它

一步一步重写 CodeIgniter 框架 (7) —— Controller执行时将 Model获

2016-07-15 00:00 393 查看
摘要: 一步一步重写 CodeIgniter 框架 (7) —— Controller执行时将 Model获得的数据传入View中,实现MVC

1. 实现过程

  1) 上一节讲述了 View 视图的加载过程,它是在 Loader 类中加载的,并通过 Include 语句进行包含。那么为了在 View 中传递变量,只需要在 include 语句所在环境的变量列表中加入这些变量即可。

  2) 另外必须考虑到可以加载多个视图,所以还要保证在前面加载视图传入的变量,后面也可以访问。

// 非常重要
if (is_array($_ci_vars)) {
$this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars);
}
extract($this->_ci_cached_vars);

  注意必须定义成员变量 $_ci_cached_vars

2. 测试

修改 test_view.php ,在标题下输出 $info



<html>
<head>
<title>My First View</title>
</head>
<body>
<h1>Welcome, we finally met by MVC, my name is Zhangzhenyu!</h1>
<p><?php echo $info ?></p>
</body>
</html>




那么相应在控制器函数中,也要改为



class welcome extends CI_Controller {

function hello() {
echo 'My first Php Framework!';
}

function saysomething($str) {
$this->load->model('test_model');

$info = $this->test_model->get_test_data();

$data['info'] = $info;

$this->load->view('test_view', $data);
}
}




3. 测试

访问 http://localhost/learn-ci/index.php/welcome/hello

可以看到输出如下

Welcome, we finally met by MVC, my name is Zhangzhenyu!

People you want in our model is Zhangzhenyu
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: