CI 中編寫自定義庫需兩文件:
application/libraries/:庫實現類application/init/:初始化腳本(自動加載)<?php
require_once('Smarty/Smarty.class.php'); // 路徑相對網站根目錄
class MySmarty extends Smarty {
function __construct() {
parent::__construct();
$basedir = dirname(__FILE__);
$this->template_dir = "$basedir/templates/";
$this->compile_dir = "$basedir/templates_c/";
$this->config_dir = "$basedir/configs/";
$this->cache_dir = "$basedir/cache/";
$this->debugging = false;
$this->cache_lifetime = 30;
$this->caching = 0;
}
}
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
if (!class_exists('MySmarty')) {
require_once(APPPATH . 'libraries/mysmarty' . EXT);
}
$CI =& get_instance();
$CI->mysmarty = new MySmarty();
$CI->ci_is_loaded[] = 'mysmarty';
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Adodb {
public $adodb;
function __construct() {
$dsn = 'mysql://user:pass@localhost/dbname';
require_once("adodb/adodb.inc" . EXT);
$this->adodb =& ADONewConnection($dsn);
$this->adodb->Execute("SET NAMES 'utf8'");
}
}
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
$CI =& get_instance();
$CI->adodb = new Adodb();
$CI->ci_is_loaded[] = 'adodb';
<?php
class Test extends Controller {
function __construct() {
parent::Controller();
$this->load->library('mysmarty');
$this->load->library('adodb');
}
function index() {
// ADOdb 查詢
$row = $this->adodb->adodb->getRow('SELECT * FROM admin');
// Smarty 賦值與渲染
$this->mysmarty->assign('row', $row);
$this->mysmarty->display('test.tpl');
}
}
require_once 路徑相對 $_SERVER['DOCUMENT_ROOT'],非當前文件目錄$this->adodb->adodb 需調用兩次,可能版本差異導致,標準用法應為 $this->adodb->getRow()(需在 Adodb 類中代理方法)__call 魔術方法代理底層對象,簡化調用{$row.name} - {$row.email}
{* Smarty 模板語法 *}
通過 CI 的庫加載機制與初始化腳本,可無縫整合 Smarty、ADOdb 等第三方庫。建議進一步封裝代理層,提供更符合 CI 風格的 API。