PDO-使用表前缀 [英] PDO - Working with table prefixes

查看:222
本文介绍了PDO-使用表前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果需要将应用程序安装到只有一个数据库的主机上,我想给表加上前缀.我想知道是否有使用PDO类处理表前缀的简单方法?

I like to prefix my tables in case I need to install the application to a host with only one database. I was wondering if there is a simple way of working with table prefixes using the PDO class?

目前,我必须覆盖自己包装的数据库中的每个方法,将%p替换为前缀,然后调用super方法.可以,但是不漂亮!

At the moment, I am having to overwrite each method in my own database wrapped, replace %p with the prefix, and call the super method. It's works, but it isn't pretty!

推荐答案

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

Extending the PDO class is probably the best option.

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);
    }
}

这篇关于PDO-使用表前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆