主从设计模式与事务一起工作

时间:2014-11-24 09:38:35

标签: php

<?php

class Database()
{
    public function __conscruct()
    {
        $dsnMaster = 'mysql:host=' . $config['host']['master'] . ';dbname=' . $config['database'] . ';charset=utf8';
        $this->dbhMaster = new PDO($dsnMaster, $config['username'], $config['password'], $options);
        $dsnSlave = 'mysql:host=' . $config['host']['slave'] . ';dbname=' . $config['database'] . ';charset=utf8';
        $this->dbhSlave = new PDO($dsnSlave, $config['username'], $config['password'], $options);
    }

    public function query($query)
    {
        if (preg_match('/^select /i', $query) > 0) {
            $this->dbh = $this->dbhMaster;
        } else {
            $this->dbh = $this->dbhSlave;
        }

        $this->stmt = $this->dbh->prepare($query);
    }

    public function execute()
    {
        return $this->stmt->execute();
    }

    public function beginTransaction()
    {
        return $this->dbh->beginTransaction();
    }
}

$db = new Database;

try {
    $db->beginTransaction();
    $db->query('SELECT * FROM `tables`');
    $db->execute();
} catch (Exception $e) {
    // rollback here
}

这是我用主从连接配置设计我的pdo函数的方法,我检查查询字符串使用SELECT来掌握和其他操作到slave,但是事务将失败因为我没有声明{ {1}} {1}},如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试添加以下行: -

$this->dbh = $this->dbhMaster

_construct函数

答案 1 :(得分:-1)

你可以使用如下

public function query($query)
    {
        if (strpos($query,'select') == 0) {
            $this->dbh = $this->dbhMaster;
        } else {
            $this->dbh = $this->dbhSlave;
        }

        $this->stmt = $this->dbh->prepare($query);
    }