CodeIgniter集成Smarty与ADODB库的实现步骤
本示例详细说明了如何在CodeIgniter框架中整合Smarty模板引擎与ADODB数据库组件。相关内容可供开发者参考借鉴。
若要在CodeIgniter中开发自定义库,必须准备两个关键文件:一是位于application/init目录下的init_myclass.php(若该目录不存在需手动创建);二是置于application/libraries目录中的myclass.php。
其中myclass代表具体的类名称。关于命名及结构的详细规则建议查阅官方手册,此处直接阐述具体操作步骤。
第一步,在application/libraries目录下分别建立mysmarty.php和adodb.php两个文件。 以下是mysmarty.php的具体代码实现:
<?php
// load Smarty library
require('Smarty/Smarty.class.php');
// The setup.php file is a good place to load
// required application library files, and you
// can do that right here. An example:
// require('guestbook/guestbook.lib.php');
class MySmarty extends Smarty {
function MySmarty()
{
// Class Constructor.
// These automatically get set with each new instance.
$this->Smarty();
$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->compile_check = true;
//this is handy for development and debugging;never be used in a production environment.
//$smarty->force_compile=true;
$this->debugging = false;
$this->cache_lifetime=30;
$this->caching = 0; // lifetime is per cache
//$this->assign('app_name', 'Guest Book');
}
}
?>
代码中的文件路径需根据实际部署情况调整。路径是相对于网站根目录(即$_SERVER['DOCUMENT_ROOT'])而言的,而非当前脚本所在的子目录。例如require('Smarty/Smarty.class.php');这一语句的路径解析起点并非application/libraries,而是网站主目录。
以下是adodb.php的具体代码实现:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Adodb
{
function Adodb()
{
//$dsn="dbdriver://username:password@server/database"
$dsn = 'mysql://user:password@localhost/xxxx';
require_once("adodb/adodb.inc".EXT);
$this->adodb =& ADONewConnection($dsn);
$this->adodb->Execute("set NAMES 'utf8'");
}
}
?>
第二步,在application/init目录下分别创建init_adodb.php和init_mysmarty.php文件。
init_adodb.php文件的代码如下:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
$obj =& get_instance();
$obj->adodb = new Adodb($obj);
$obj->ci_is_loaded[] = 'adodb';
</code></pre>
init_mysmarty.php文件的代码如下:
<pre class="brush:php;"><code class="language-php">
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if ( ! class_exists('MySmarty'))
{
require_once(APPPATH.'libraries/mysmarty'.EXT);
}
$obj =& get_instance();
$obj->mysmarty = new MySmarty();
$obj->ci_is_loaded[] = 'mysmarty';
?>
第三步,进行调用测试。 在application/controllers目录下新建一个控制器文件,即可按以下方式调用ADODB和Smarty。
<?php
class Test extends Controller {
function Test()
{
parent::Controller();
$this->load->library('mysmarty');
$this->load->library('adodb');
}
function index()
{
$this->load->library('adodb');
$row = $this->adodb->adodb->getrow('SELECT * FROM admin');
$this->mysmarty->assign("row",$row);
$this->mysmarty->display("test.tpl");
}
}
?>
此处出现两次ADODB实例化的原因尚不明确,依据官方文档通常只需一次。尽管该方法在我本地环境中报错,可能源于对CodeIgniter机制理解不足,待后续深入研究后再行优化。但目前此方案可确保功能正常运作。
期望上述内容能对从事PHP程序设计的读者提供有益帮助。