Home

Awesome

CakePHP Master Replica Plugin

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

Supports

:bulb: For CakePHP3.x, use 1.x branch.

Usage

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

Example

Set up your database configuration.

// 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 :tada:

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

// switch to `replica` role
\Cake\Datasource\ConnectionManager::get('default')->switchRole('secondary');
// Or you can get Connection via Table
$usersTable->getConnection()->switchRole('tertiary');

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/Connehito/cakephp-master-replica

License

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