2009-09-24 60 views
7

如果我需要将应用程序安装到只有一个数据库的主机,我喜欢在我的表前加上字。我想知道是否有一种使用PDO类的表前缀工作的简单方法?PDO - 使用表前缀

目前,我不得不覆盖我自己的数据库包装中的每个方法,用前缀替换%p,并调用super方法。这是有效的,但它不漂亮!

回答

9

扩展PDO类可能是最好的选择。

class MyPDO extends PDO 
{ 
    protected $_table_prefix; 
    protected $_table_suffix; 

    public function __construct($dsn, $user = null, $password = null, $driver_options = array(), $prefix = null, $suffix = null) 
    { 
     $this->_table_prefix = $prefix; 
     $this->_table_suffix = $suffix; 
     parent::__construct($dsn, $user, $password, $driver_options); 
    } 

    public function exec($statement) 
    { 
     $statement = $this->_tablePrefixSuffix($statement); 
     return parent::exec($statement); 
    } 

    public function prepare($statement, $driver_options = array()) 
    { 
     $statement = $this->_tablePrefixSuffix($statement); 
     return parent::prepare($statement, $driver_options); 
    } 

    public function query($statement) 
    { 
     $statement = $this->_tablePrefixSuffix($statement); 
     $args  = func_get_args(); 

     if (count($args) > 1) { 
      return call_user_func_array(array($this, 'parent::query'), $args); 
     } else { 
      return parent::query($statement); 
     } 
    } 

    protected function _tablePrefixSuffix($statement) 
    { 
     return sprintf($statement, $this->_table_prefix, $this->_table_suffix); 
    } 
} 
+0

喜只是我还是在功能/法'_tablePrefixSuffix'最后一位'$ this_table_suffix'是它假设是'$此 - > _ table_suffix'? – Val 2012-06-18 13:18:53

+0

不知道这可能被认为是工作示例,因为'sprintf'需要带有特殊锚的格式化字符串,但'$ statement'参数只是一个普通字符串,它只是被忽略并按原样返回。 – 2012-09-20 08:01:52

+0

好的,算出来。您只需使用锚点指定表名:'$ table =“%1 \ $ s {$ table}%2 \ $ s”' – 2012-09-20 08:26:39