PHP code example of code-distortion / swap-con

1. Go to this page and download the library: Download code-distortion/swap-con 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/ */

    

code-distortion / swap-con example snippets

 php
// alter the connection for a particular query
DB::connection('mysql2')->table('users')->all();
 php
// hard-code the connection a model uses
class SomeModel extends Eloquent {
    protected $connection = 'mysql2';
}
// or change the connection for a particular model instance
$someModel = new SomeModel;
$someModel->setConnection('mysql2');
$someModel->find(1);
 php
// specify read/write connections in config/database.php
'mysql' => [
    'read' => [
        'host' => [
            '192.168.1.1',
            '196.168.1.2',
        ],
    ],
    'write' => [
        'host' => [
            '196.168.1.3',
         ],
    ],
    'sticky'    => true,
    'driver'    => 'mysql',
    'database'  => 'database',
    …
],
 php
'providers' => [
    …
    CodeDistortion\SwapCon\SwapConServiceProvider::class,
    …
],
'aliases' => [
    …
    'SwapCon' => CodeDistortion\SwapCon\SwapConFacade::class,
    …
],
 bash
php artisan vendor:publish --provider="CodeDistortion\SwapCon\SwapConServiceProvider" --tag="config"
 php
// change the current database
SwapCon::useDB('mysql2'); // or ->useDatabase(..)
 php
// config/database.php
'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '192.168.1.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'mydb_rw'),
    …
],
'mysql-ro' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '192.168.1.2'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'mydb_ro'),
    …
],
 php
SwapCon::swapDB('mysql-ro', $callback);
 php
SwapCon::SwapDB('mysql-ro', $callback);
 php
// config/code-distortion.swapcon.php
'fallbacks' => [
    'reuse' => [
        'database' => [
            'mysql-ro' => 'mysql',
        ],
    ],
    'clone' => [
        'database' => [
//            'mysql-ro' => 'mysql',
        ],
    ],
],
 php
SwapCon::updateDB('tenant', ['database' => $tenantDB]);