在網頁上,有些複雜而獨立的功能須要常用。
之前的方法是使用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