PDO - 使用表前缀

时间:2009-09-24 14:55:48

标签: php mysql pdo

我喜欢为我的表添加前缀,以防我需要将应用程序安装到只有一个数据库的主机上。我想知道是否有一种使用PDO类处理表前缀的简单方法?

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

1 个答案:

答案 0 :(得分: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);
    }
}