Using MongoDB Replica Sets With the Lithium Framework

It's pretty flexible now with the latest PHP driver once you figure out the changes.

Posted 2 years ago by Tom Maiaroto.


So I noticed on a recent job that my secondary database wasn't being used by my code. I was confused because in the past it always did. Though it was with the "slaveOk" setting and I know that things changed since then in the PHP driver but I thought Lithium automatically send reads to the secondary (if configured in the connection). It does not.

However, you still need to make sure you pass all servers you wish to connect to in the connection configuration. Don't forget you can pass host names and the port number is optional in this string. However, each host is set in a comma separated string and not an array or anything.


Connections::add('default', array(
        'type' => 'MongoDb',
        'host' => 'db1,db2,db3:27017',
        'replicaSet' => true,
        'database' => 'myProject'
));

Then after that, you can choose which queries will use the secondary databases with the following bit.


$db = MyModel::connection();
$db->connection->setReadPreference(MongoClient::RP_SECONDARY_PREFERRED);
MyModel::find(...);

Actually, with the new readPreference option that MongoDB has, you can do a lot more than that. You can tag your servers and choose which ones to use and when to use them. Look at all of the options here. Ensure that you have the proper Mongo PHP driver from PECL as things have changed quite a bit in the last few versions.


Filed under
comments powered by Disqus

Search for Posts

Popular Labels

social media virality score general internet web development reviews and opinions php web tools hosting lithium web design

Recent Posts