PHP code example of karol-dabrowski / doctrine-dynamic-connection

1. Go to this page and download the library: Download karol-dabrowski/doctrine-dynamic-connection 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/ */

    

karol-dabrowski / doctrine-dynamic-connection example snippets



// bootstrap.php
s\Setup;
use Doctrine\ORM\EntityManager;
use DynamicConnection\DynamicConnectionWrapper;
use DynamicConnection\DynamicEntityManager;

// the connection configuration
$dbParams = array(
    'driver'   => 'pdo_mysql',
    'user'     => 'root',
    'password' => 'pass',
    'dbname'   => 'db_name',
    'wrapperClass' => DynamicConnectionWrapper::class
);

$isDevMode = true;
$proxyDir = null;
$cache = null;
$useSimpleAnnotationReader = false;

$config = Setup::createAnnotationMetadataConfiguration(
    array(__DIR__."/src"),
    $isDevMode,
    $proxyDir,
    $cache,
    $useSimpleAnnotationReader
);

// For XML mappings
// $config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);

// For YAML mappings
// $config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);

$entityManager = EntityManager::create($dbParams, $config);
$dynamicEntityManager = new DynamicEntityManager($entityManager);

public function modifyConnection(
    ?string $databaseName = null,
    ?string $username = null,
    ?string $password = null,
    ?string $host = null,
    ?string $port = null
): void;



// Change database name
$dynamicEntityManager->modifyConnection('new_db_name');

// Change database name and database user
$dynamicEntityManager->modifyConnection('new_db_name', 'username', 'password');

// Change database user and leave database name unchanged
$dynamicEntityManager->modifyConnection(null, 'username', 'password');

// Change only database host and port, leave database name and user unchanged
$dynamicEntityManager->modifyConnection(null, null, null, '127.0.0.2', '3307');

// Change database name, host and port, leave database user unchanged
$dynamicEntityManager->modifyConnection('new_db_name', null, null, '127.0.0.2', '3307');

// Change all parameters
$dynamicEntityManager->modifyConnection('new_db_name', 'username', 'password', '127.0.0.2', '3307');