ZendFramework 使用数据表前缀

目录结构

zend framework dirs

在 config.ini 定义 prefix

[general]
adapter  = PDO_MYSQL
host     = localhost
username = root
password = 123456
dbname   = test
charset  = utf8
prefix   = pf_    //表前缀

index.php 中将 prefix 注册

// 读取数据库配置
$dbconfig = new Zend_Config_Ini('../config/config.ini', 'general');

// 配置数据库
$database = Zend_Db::factory($dbconfig->adapter,$dbconfig->toArray());

// 设置数据库编码
$database->query("set names {$dbconfig->charset};");

Zend_Db_Table::setDefaultAdapter($database);
Zend_Registry::set('database',$database);

// 数据表前缀
Zend_Registry::set('dbprefix',$dbconfig->prefix);

在 library/Custom 目录下新建文件 Db.php 继承 Zend_Db_Table 类

class Custom_Db extends Zend_Db_Table
{
    public function __construct()
    {
        $dbprefix = Zend_Registry::get('dbprefix');
        $this->_name = $dbprefix.$this->_name;
        parent::__construct();
    }
}

最后在 model 中继承 Custom_Db 即可

class User extends Custom_Db
{
    protected $_name = 'users';     //在Custom_Db中会自动加上表名的前缀
    protected $_primary = 'userid'; //主键
}
2008-01-17 111 dbprefix php zendframework