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 注册

  1. // 读取数据库配置
  2. $dbconfig = new Zend_Config_Ini('../config/config.ini', 'general');
  3. // 配置数据库
  4. $database = Zend_Db::factory($dbconfig->adapter,$dbconfig->toArray());
  5. // 设置数据库编码
  6. $database->query("set names {$dbconfig->charset};");
  7. Zend_Db_Table::setDefaultAdapter($database);
  8. Zend_Registry::set('database',$database);
  9. // 数据表前缀
  10. Zend_Registry::set('dbprefix',$dbconfig->prefix);

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

  1. class Custom_Db extends Zend_Db_Table
  2. {
  3.     public function __construct()
  4.     {
  5.         $dbprefix = Zend_Registry::get('dbprefix');
  6.         $this->_name = $dbprefix.$this->_name;
  7.         parent::__construct();
  8.     }
  9. }

最后在 model 中继承 Custom_Db 即可

  1. class User extends Custom_Db
  2. {
  3.     protected $_name = 'users';     //在Custom_Db中会自动加上表名的前缀
  4.     protected $_primary = 'userid'; //主键
  5. }
Tags: dbprefix, php, zendframework

相关日志

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)


*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Comment moderation is enabled. Your comment may take some time to appear.