結合起來,這兩個帖子幫助我解決了我自己非常類似的問題。這裏是我的解決方案,也許是別人有用:
<?php
namespace Calitarus\CollaborationBundle\EventListener;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\DBAL\Connection;
use Exception;
use Monolog\Logger;
class DatabaseSwitcherEventListener {
private $request;
private $connection;
private $logger;
public function __construct(Request $request, Connection $connection, Logger $logger) {
$this->request = $request;
$this->connection = $connection;
$this->logger = $logger;
}
public function onKernelRequest() {
if ($this->request->attributes->has('_site')) {
$site = $this->request->attributes->get('_site');
$connection = $this->connection;
$params = $this->connection->getParams();
$db_name = 'br_'.$this->request->attributes->get('_site');
// TODO: validate that this site exists
if ($db_name != $params['dbname']) {
$this->logger->debug('switching connection from '.$params['dbname'].' to '.$db_name);
$params['dbname'] = $db_name;
if ($connection->isConnected()) {
$connection->close();
}
$connection->__construct(
$params, $connection->getDriver(), $connection->getConfiguration(),
$connection->getEventManager()
);
try {
$connection->connect();
} catch (Exception $e) {
// log and handle exception
}
}
}
}
}
爲了得到這個工作,我設置了services.yml如下:
services:
cc.database_switcher:
class: Calitarus\CollaborationBundle\EventListener\DatabaseSwitcherEventListener
arguments: [@request, @doctrine.dbal.default_connection, @logger]
scope: request
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
,我有這樣的路由配置得到在_site參數,這在我的情況是URL的一部分,但你可以根據你的設置可能會得到它在其他方面:
resource: "@CCollabBundle/Controller"
type: annotation
prefix: /{_site}
defaults:
_site: default
來源
2014-07-05 10:09:04
Tom
也收拾這一點,所以主義與默認連接的注入,因此可以去除ContainerAware延伸。 – catchamonkey 2013-02-27 12:15:55
$ this-> request->屬性來自哪裏? – 2015-09-25 14:31:42