Created
October 27, 2015 22:34
-
-
Save markitosgv/b0dd51c9d1e3ef135648 to your computer and use it in GitHub Desktop.
Database Switch Event Listener (Symfony2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you need to change default connection, providing a ENV variable