CodeIgniter增长widget功能

在网页上,有些复杂而独立的功能须要常用。
之前的方法是使用common function的方法达到复用的效果。php

接触了Yii、shopex后,就想试试给CI也加一个相似的功能。毕竟以wedget方式独立每一个组件比common function更直观和可配置性。html

首先,在application目录下新建widgets文件夹。
全部widget都在其下创建子目录,目录命名规则为
1.驼峰格式且首字母小写
2.以Weidget结尾
例如,创建一个first挂件,那么在application/widgets下创建目录firstWidget.web

挂件文件夹
1.主要存放视图及配置文件。
2.每个挂件在调用时,都会自动加载配置文件config.php。
config.php文件数据格式以下:app

<?php

/*
* 做者:alson_zhow
* 挂件名称:测试挂件
* 挂件配置文件
*/
return array(
'author' => '挂件做者',
'version'=> '关键版本',
'name' => '挂件名称',
'description'=>'挂件描述',
'template' => array(
'default' => '默认', //默认挂件视图名必须为default
'ceshi' => '自定义测试'
)
);
?>webapp

目录格式已经了解,下面就是挂架lib的创建
进入application/libraries/创建Widget.php.
代码以下:测试

<?php

/*
* 做者:晋勇
* widget支持
* 基于application/widgets目录
*/
class Widgets extends Cismarty {fetch

protected $basePath = null;//widgets跟路径  
protected $check = false;//文件夹检查  

function  __construct() {  
    parent::__construct();  
    $this->basePath = APPPATH.'widgets/';  
    is_dir($this->basePath) ? is_readable($this->basePath) ? $this->check = true : 1 : 1;  
    if(!$this->check) die('widgets配置不正确');  
}  
/** 
 * 调用挂件 
 * 
 * @param String $name 挂件名 
 * @param template $tpl 模板选择 
 * @param array $data 传递数据 
 * @return String 挂件内容缓冲 
 */  
function get($params){  
    $tpl = 'default';//默认挂件视图文件名为default  
    $data= null;  
    extract($params);  
    //加载挂件配置文件  
    $config = $this->basePath.$name.'Widget/'.'config.php';  
    if(is_readable($config)){  
        if($tpl != 'default')  
            $tpl = $this->basePath.$name.'Widget'.'/'.$tpl.'.'.$this->ext;  

        if(is_readable($tpl)){  

            if($data){  
                foreach($data as $key=>$value){  
                    $this->assign($key,$value);  
                }  
            }  
            $output = $this->fetch($tpl);  
        }else{  
            $output = '挂件不存在';  
        }  
    }else{  
        $output = '挂件缺乏配置文件';  
    }  
    return $output;  
}

}
?>this

下面配置CI的autoload.php,在$autoload['libraries'] 中加入'widget'.
此篇文章的挂件是基于smarty模板引擎的,若是您的CI还未支持smarty能够先阅读CI挂载smarty 。
下面是对widget的使用示例
application/controllers下创建test.phpcode

<?php

/*
* 做者:alson_zhow
*/
class Test extends Controller {
function index(){
$output = $this->widgets->get(array('name'=>'first','tpl'=>'first','data'=>array('number'=>4)));
$this->cismarty->assign('widget',$output);
$this->cismarty->show('index');
}
}
?>
application/views下创建index.tplhtm

<html>

<!--{$info}-->
<!--{$widget}-->
</html>

application/widgets/下创建firstWidget文件夹并创建first.tpl及config.php
代码分别以下:

<div>This is the <!--{$number}--> widget</div>  

<?php

/*
* 做者:alson_zhow
* 挂件名称:测试挂件一
* 挂件配置文件
*/
return array(
'author' => '挂件做者',
'version'=> '关键版本',
'name' => '挂件名称',
'description'=>'挂件描述',
'template' => array(
'default' => '默认', //默认挂件视图名必须为default
'ceshi' => '自定义测试'
)
);
?>
最后访问:http://hostname/webapp/test 返回结果就不截图了。就是一串简单字符 Hello World! This is the 4 widget

相关文章
相关标签/搜索