Skip to content

Instantly share code, notes, and snippets.

@markitosgv
Created October 27, 2015 22:34
Show Gist options
  • Save markitosgv/b0dd51c9d1e3ef135648 to your computer and use it in GitHub Desktop.
Save markitosgv/b0dd51c9d1e3ef135648 to your computer and use it in GitHub Desktop.
Database Switch Event Listener (Symfony2)
<?php
namespace AppBundle\EventListener;
use Doctrine\DBAL\Connection;
class DatabaseSwitcherEventListener
{
private $connection;
public function __construct(Connection $connection)
{
$this->connection = $connection;
}
public function onKernelRequest()
{
$connection = $this->connection;
if (!$connection->isConnected()) {
$params = $this->connection->getParams();
$params['dbname'] = getenv('SYMFONY__DATABASE__NAME') ? getenv('SYMFONY__DATABASE__NAME') : $params['dbname'];
$connection->__construct(
$params,
$connection->getDriver(),
$connection->getConfiguration(),
$connection->getEventManager()
);
$connection->connect();
}
}
}
@markitosgv
Copy link
Author

If you need to change default connection, providing a ENV variable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment