PHP code example of connehito / cakephp-master-replica

1. Go to this page and download the library: Download connehito/cakephp-master-replica library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

connehito / cakephp-master-replica example snippets


// 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'],
        ]
    ]

// 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');