Provides the features for multiple database connections as master/replica and switching.

2.0.0 2020-02-24 06:35 UTC

This package is auto-updated.

Last update: 2020-09-20 17:24:09 UTC


The datasource for CakePHP.This plugin enables one-connection to act as two(or more) roles, like master(read-write) and replica(read-only).

Build Status codecov Latest Stable Version Total Downloads License


  • PHP 7.2+
  • CakePHP 4.0+

💡 For CakePHP3.x, use 1.x branch.


  1. Install plugin composer require connehito/cakephp-master-replica
  2. Set your connections(e.g. in config/app.php datasource. It requires roles property.


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=db-host,databasename=app_db,login=read-only-user,pass=another-password
  • Databse-C(for replica): mysql;host=replica-host,databasename=app_db,login=read-only-user,pass=another-password
// app.php
// return [
    'Datasources' => [
        'driver' => Cake\Database\Driver\Mysql::class,
        'className' => Connehito\CakephpMasterReplica\Database\Connection\MasterReplicaConnection::class,
        'host' => 'replica-host',
        'database' => 'app_db',
        'roles' => [
            'master' => ['host' => 'db-host', 'username' => 'root', 'password' => 'password'],
            'secondary' => ['host' => 'db-host', 'username' => 'read-only-user', 'password' => 'another-password'],
            'tertiary' => ['username' => 'read-only-user', 'password' => 'another-password'],

In each roles, you can set specific values and override them.

In app, now you can connect to database master or replica db as you like 🎉

// as default, connect with `master` role.
$usersTable->save($usersTable->newEnitty(['name' => 'hoge']));

// switch to `replica` role
// Or you can get Connection via Table


Bug reports and pull requests are welcome on GitHub at

  • Please fix all problems with PHPUnit, PHPStan, PHP_CodeSniffer before send pull request 😄
  • You can build development env in local with tests/test_app/docker-compose.yml 🏇


The plugin is available as open source under the terms of the MIT License.