How to create a "mode switch" for PHP PDO?

I am currently using PHP PDO to access my database. All this works great and dandy. However, I'm going to add read replicas to the server setup, so I want to adjust the code accordingly.

My current plan of action is to store an array of database credential data. One read and write is set for the main MySQL database and any number of credentials for read replicas.

I want to add a method of the PDO class called "mode", in which, for example, "read" or (default) "write" is transmitted through mode. Passing this through (for example, the $ dbh-> ("read"); mode), he can look for details of a randomly read replica (no fuss) and use these details to connect. Then, when I finished reading from my replicas, do another $ dbh-> ("default") mode to put it back in write mode, so I can use INSERT, UPDATE, etc.

Can this be done without simply destroying the PDO and creating a new one? Is it possible to change the connection parameters after the object already exists?

So far I have had the following (it is almost nothing, but it occurred to me).

Class SwitchablePDO extends PDO
{
    public function mode($mode = "default") 
    {
        // Use the credentials for my master read and write server by default

        if($mode == "read")
        {
            // Use one the credentials for my read replicas (randomly choose)
        }

    }
}

Any help in this regard would be appreciated!

+5
2

, . , , , . .

, factory , , , , , .

master/slave , , , , , , , .

+2

, , , / SwitchablePDO. mode() , . :

class WriteablePDO extends PDO
{
    // methods
}

class ReadablePDO extends PDO
{
    // methods
}

class SwitchablePDO
{
    protected $_mode = 'read'; // default
    protected $_read;
    protected $_write;

    public function __construct()
    {
        $this->_read = new ReadablePDO();
        $this->_write = new WriteablePDO();
    }

    public function mode($key)
    {
        if ($key === 'read')
        {
            $this->_mode = '_read';
        }
        elseif ($key === 'write')
        {
            $this->_mode = '_write';
        }
    }

    public function __call($method, $arguments)
    {
        return call_user_func_array(array($this->{$this->_mode}, $method), $arguments);
    }

}
+1

All Articles