Created
August 23, 2017 12:14
-
-
Save zak10/6dcd9bbe33cf7a2f0c339442db293e9a to your computer and use it in GitHub Desktop.
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
// services.yml | |
catalog.kernel.request_event_listener: | |
class: App\CoreBundle\EventListener\KernelBootDatabaseSwitchListener | |
arguments: [@request, @doctrine.dbal.default_connection, @logger] | |
scope: request | |
tags: | |
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest } | |
// KernelContextListener | |
/** | |
* KernelContextListener constructor. | |
* @param Request $request | |
* @param Connection $connection | |
* @param $logger | |
*/ | |
public function __construct(Request $request, Connection $connection, Logger $logger) | |
{ | |
$this->request = $request; | |
$this->connection = $connection; | |
$this->logger = $logger; | |
} | |
/** | |
* | |
* @throws MissingSiteException | |
* @throws \Doctrine\DBAL\DBALException | |
*/ | |
public function onKernelRequest() | |
{ | |
if ($this->request->get('site')) { | |
$siteId = $this->request->get('site'); // every request needs site as a param, can change to domain parsing or whatever logic | |
$connection = $this->connection; | |
$connectionParameters = $this->connection->getParams(); | |
$databaseName = sprintf("client_%d", $siteId); // here you figure out the database based on the site | |
$this->logger->debug(sprintf("Switching kernel context to use database %s", $databaseName)); | |
$connectionParameters['dbname'] = $databaseName; | |
if ($connection->isConnected()) { | |
$connection->close(); | |
} | |
// Reconstruct the DB connection and try to connect | |
$connection->__construct($connectionParameters, $connection->getDriver(), $connection->getConfiguration(), $connection->getEventManager()); | |
$connection->connect(); | |
// if we can't connect, panic | |
if (!$connection->isConnected()) { | |
throw new ConnectionException(sprintf("Couldn't connect to database %s", $databaseName)); | |
} | |
} else { | |
throw new MissingSiteException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment