Create a Doctrine DBAL Connection for Another Database

There are 3 ways to create a DBAL connection to access another database:

\Doctrine\Bundle\DoctrineBundle\ConnectionFactory

/** @var \Doctrine\Bundle\DoctrineBundle\ConnectionFactory $connectionFactory */
$connectionFactory = $this->getContainer()->get('doctrine.dbal.connection_factory');
$connection = $connectionFactory->createConnection([
	'pdo' => new \PDO(
		"mysql:host=$hostname;dbname=$dbname", 
		$username, 
		$password)
]);

$connection->executeQuery('SELECT * FROM your_table');

\Doctrine\DBAL\DriverManager

/**
 * Creates connection based on application configuration.
 */
function createConnection(): \Doctrine\DBAL\Connection
{
    $config = new \Doctrine\DBAL\Configuration();
    $parser = new \Symfony\Component\Yaml\Parser();
    $configParams = $parser->parse(file_get_contents(getcwd() . '/config/parameters.yml'));
    $configParams = $configParams['parameters'];

    return \Doctrine\DBAL\DriverManager::getConnection([
        'dbname' => $configParams['database_name'],
        'user' => $configParams['database_user'],
        'password' => $configParams['database_password'],
        'host' => $configParams['database_host'],
        'driver' => $configParams['database_driver']
    ], $config);
}
public function exSQL()
{


    $config = new \Doctrine\DBAL\Configuration();

    $connectionParams = array(
        'dbname' => 'dbname',
        'user' => 'user',
        'password' => 'password',
        'host' => 'prod_host',
        'driver' => 'pdo_mysql',
    );
    $conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);


    $sql = "SELECT ...";
    $stmt = $conn->query($sql); 

    while ($row = $stmt->fetch()) {
        var_dump($row);
    }

    // This works !!!


}

\Doctrine\ORM\EntityManager

src\Stars\Bundle\LoggerEventBundle\Resources\config\oro\app.yml

doctrine:
    dbal:
        connections:
            emgsihe:
                driver:   pdo_mysql
                host:     '%database_host%'
                port:     '%database_port%'
                dbname:   emgsihe
                user:     '%database_user%'
                password: '%database_password%'
                charset:  UTF8
    orm:
        entity_managers:
            emgsihe:
                connection: emgsihe
// ...

use \Doctrine\ORM\EntityManager;
//...

public function __construct(EntityManager $entityManager)
{
    $this->entityManager = $entityManager;
}

public function exSQL($conn_name)
{

    $conn = $this->entityManager->getConnection($conn_name);

    $sql = "SELECT ...";
    $stmt = $conn->query($sql); 

    while ($row = $stmt->fetch()) {
        var_dump($row);
    }   

} 
kiatng over 3 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more