首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

CodeIgniter 整合 Smarty 模板引擎與 ADOdb 數據庫庫完整步驟

     編輯:PHP 相關知識

架構說明

CI 中編寫自定義庫需兩文件:

  1. application/libraries/:庫實現類
  2. application/init/:初始化腳本(自動加載)

一、Smarty 整合

1. 庫文件 (libraries/mysmarty.php)

<?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;
    }
}

2. 初始化腳本 (init/init_mysmarty.php)

<?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';

二、ADOdb 整合

1. 庫文件 (libraries/adodb.php)

<?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'");
    }
}

2. 初始化腳本 (init/init_adodb.php)

<?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');
    }
}

關鍵注意點

  1. 路徑基準:require_once 路徑相對 $_SERVER['DOCUMENT_ROOT'],非當前文件目錄
  2. 雙重調用:作者發現 $this->adodb->adodb 需調用兩次,可能版本差異導致,標準用法應為 $this->adodb->getRow()(需在 Adodb 類中代理方法)
  3. 改進建議:在 Adodb/MySmarty 類中實現 __call 魔術方法代理底層對象,簡化調用

模板文件示例 (test.tpl)

{$row.name} - {$row.email}
{* Smarty 模板語法 *}

總結

通過 CI 的庫加載機制與初始化腳本,可無縫整合 Smarty、ADOdb 等第三方庫。建議進一步封裝代理層,提供更符合 CI 風格的 API。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved