connehito / cakephp2-master-replica
Provides the features for multiple database connections as master/replica and switching in Datasource.
Installs: 3 784
Dependents: 0
Suggesters: 0
Security: 0
Stars: 7
Watchers: 1
Forks: 0
Open Issues: 0
Type:cakephp-plugin
This package is auto-updated.
Last update: 2024-10-29 05:59:53 UTC
README
The datasource for CakePHP(2.x).This plugin enables one-connection to act as two(or more) roles, like master(read-write) and replica(read-only).
Supports
- PHP 5.6+ / 7.0+
- CakePHP 2.7+
- MySQL
Usage
- Download the repository to set
app/Plugin/MasterReplica
- Load plugin in
app/Config/bootstrap.php
likeCakePlugin::load('MasterReplica');
orCakePlugin::loadAll();
- Set your
database.php
withMasterReplica.Database/MasterReplicaMysql
datasource. It requiresconnections
property.
Example
Set up your database configuration.
- Databse-A(for master): mysql;host=db-host,databasename=app_db,login=root,pass=password
- Databse-B(for replica): mysql;host=replica-host,databasename=app_db,login=read-only-user,pass=another-password
// database.php <?php class DATABASE_CONFIG { public $default = array( 'datasource' => 'MasterReplica.Database/MasterReplicaMysql', 'persistent' => true, // default connection role(optional) 'connection_role' => 'master', 'connections' => array( // shared values(you can leave this values empty, but must be declared) '_common_' => array( 'database' => 'app_db', ), // default connection values 'master' => array( 'host' => 'db-host', 'login' => 'root', 'password' => 'password', ), // `secondary` role connection values 'secondary' => array( 'host' => 'replica-host', 'login' => 'read-only-user', 'password' => 'another-password', ), ), ); }
In app, now you can connect to database master or replica db as you like 🎉
$Post = ClassRegistry::init('Post'); // as default, connect with `master` role. $Post->save(array('Post' => array('user_id' => 10, 'title' => 'new post', 'content' => 'some content'))); // switch to `replica` role $conn = $this->Post->getDataSource(); $conn->switchConnectionRole('secondary');
License
The plugin is available as open source under the terms of the MIT License.