在网页上,有些复杂而独立的功能需要经常使用。
以前的方法是使用common function的方法达到复用的效果。
接触了Yii、shopex后,就想试试给CI也加一个类似的功能。毕竟以wedget方式独立每个组件比common function更直观和可配置性。
首先,在application目录下新建widgets文件夹。
所有widget都在其下建立子目录,目录命名规则为
1.驼峰格式且首字母小写
2.以Weidget结尾
例如,建立一个first挂件,那么在application/widgets下建立目录firstWidget.
挂件文件夹
1.主要存放视图及配置文件。
2.每一个挂件在调用时,都会自动加载配置文件config.php。
config.php文件数据格式如下:
<?php
/*
* 作者:alson_zhow
* 挂件名称:测试挂件
* 挂件配置文件
*/
return array(
'author' => '挂件作者',
'version'=> '关键版本',
'name' => '挂件名称',
'description'=>'挂件描述',
'template' => array(
'default' => '默认', //默认挂件视图名必须为default
'ceshi' => '自定义测试'
)
);
?>
目录格式已经了解,下面就是挂架lib的建立
进入application/libraries/建立Widget.php.
代码如下:
<?php
/*
* 作者:晋勇
* widget支持
* 基于application/widgets目录
*/
class Widgets extends Cismarty {
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;
}
}
?>
下面配置CI的autoload.php,在$autoload['libraries'] 中加入'widget'.
此篇文章的挂件是基于smarty模板引擎的,如果您的CI还未支持smarty可以先阅读CI挂载smarty 。
下面是对widget的使用示例
application/controllers下建立test.php
<?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.tpl
<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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。