I am currently using PHP PDO to access my database. That is all working absolutely fine and dandy. However, I am going to be adding read-replicas to my server setup, so I wish to adjust my code accordingly.
My current plan of action is to store an array of database credential details. One “read and write” set for the master MySQL database and any number of credentials for “read replicas”.
What I wish to do is add a method to the PDO class called “mode” where by a mode is passed through, such as “read” or (default) “write”. By passing this through (eg. $dbh->mode(“read”); ), it can lookup the details of a random read replica (not fussed which) and use those details for the connection. Then once i’m done reading from my replicas, do another $dbh->mode(“default”) to put it back into write mode, whereby I can use INSERT, UPDATE etc.
Can this be done without simply destroying the PDO object and creating a new one? Can connection details simply be changed after the object already exists?
So far I have the following (its barely anything, but figured its a start).
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 regarding this would be appreciated!
I would rather set-up completely different database connection objects than deal with a mode. Using a mode, you will inevitably run into a situation where a piece of code does not set the mode and relies on the previous piece of code’s mode, and will fail when called in a different context. This is known as sequential coupling.
With multiple objects provided by a factory method, or a dependency injection container, you make sure each piece of code specifies which database connection it needs, such as master or slave.
As a bonus, avoid using master/slave as a name and instead use names that relate to the type of tasks to be performs, like analytics, which allows you to change which server will be used without going through the code to find all related pieces of code.