用户
 找回密码
 入住 CI 中国社区
搜索
查看: 5047|回复: 1
收起左侧

Codeigniter 实现两步视图

[复制链接]
发表于 2008-12-18 19:24:09 | 显示全部楼层 |阅读模式
转自:http://hi.baidu.com/andycai/

要实现想Zend fromework 中的 layout,所谓的“the Two Step View pattern”,只需要在扩展 CI 的控制器,详细的代码和说明请参阅原文,如上的链接。

在这里我只是简单的说明一下思路,通过继承 CI 的控制器类显示自己的 MY_Controller 类,这个类会加载一些默认的数据,并且会有一个 render 函数来实现“两步视图”。参照 Zend framework 中的做法,会在 views 下面创建一个以控制器类命名的文件夹并在这个文件夹下创建一个以动作(action)命名的默认模板文件,让render 函数自动加载。rendre 函数首先会判断这个默认(action)的模板文件是否存在,如果存在就将模板的内容赋值给“第一步视图”(即 layout 文件)变量 ’content‘ ,这个变量会注入到“第一步视图”文件中。

原文作者使用了 PHP5 类的写法来扩展 CI 的控制器,你可以自行修改为 PHP4 版本,更详细的代码和说明请参阅原文。

Layout 文件:

HTML复制代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" c />
<title><?php echo $title; ?></title>
 
<?php echo $css; ?>
 
</head>
 
<body>
    <div id="page">
 
        <div id="header">
            <h1><?php echo $title; ?></h1>
            <?php $this->load->view('partials/menu.tpl.php'); ?>
        </div>
 
        <div id="content">
            <h2><?php echo $heading; ?></h2>
            <?php echo $content; ?>            
        </div>
 
        <div id="footer">
            <p>© 2008 AVNet Labs.</p>
        </div>
 
    </div>
</body>
</html>
复制代码


控制器类:

PHP复制代码
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
 
class MY_Controller extends Controller {
 
 protected $data = array();
 protected $class_name;
 protected $action;
 protected $param;
 
 public function __construct() {  
                parent::__construct();
  $this->load_defaults();
        }
 
 protected function load_defaults() {
  $this->data['heading'] = 'Page Heading';
  $this->data['content'] = '';
  $this->data['css'] = '';
  $this->data['title'] = 'Page Title';
 
  $this->class_name = strtolower(get_class($this));
  $this->action = $this->uri->segment(2, 'index');
 
 }
 
 protected function render($template='main') {
 
  if (file_exists(APPPATH . 'views/' . $this->class_name . '/' . $this->action . '.tpl.php')) {
   $this->data['content'] .= $this->load->view($this->class_name . '/' . $this->action .
 '.tpl.php', $this->data, true);
  }
 
  $this->load->view("layouts/$template.tpl.php", $this->data);
 }
 
 protected function add_css($filename) {
  $this->data['css'] .= $this->load->view("partials/css.tpl.php", array(
'filename' => $filename), true);
 }
 
}
?>
复制代码

评分

参与人数 1威望 +5 收起 理由
Hex + 5 精品文章

查看全部评分

发表于 2008-12-18 23:03:34 | 显示全部楼层
我帮楼主改一下语法加亮。
再次感谢楼主的教程!

本版积分规则