我有一个简单的Symfony2应用程序,它需要基于子域连接到特定的数据库。数据库名称与子域名相同。
域:alpha.example.com - DB名称:alpha
域:beta.example.com - DB名称:beta
按照我的想法,实现这一点的最简单方法是将当前的子域传递到config.yml文件中。
#config.yml
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "current-subdomain-name-here"
user: "%database_user%"
password: "%database_password%"问题是如何在config.yml中传递和访问当前的子域名。
发布于 2014-12-16 11:08:53
我会避免把这个放进app.php。也许您也需要在app_dev.php中使用相同的代码来进行开发和测试。
每个子域一个配置文件看起来也不太方便。
看一看:
在那里,您可以做类似于(未测试)的事情:
# app/config/config.yml
imports:
- { resource: parameters.php }-
// app/config/parameters.php
$subdomain = array_shift((explode(".",$_SERVER['HTTP_HOST'])));
$container->setParameter('doctrine.dbal.dbname', $subdomain);发布于 2014-12-14 17:44:01
我认为这是不可能的,但无论如何,配置文件不应该包含任何应用程序逻辑。
您可以按照食谱中解释的关于多个管理人员和连接的指令,然后创建逻辑(例如使用依赖注入服务),但是实现取决于您的特定用例,我不知道具体用例。
发布于 2014-12-14 18:30:59
您不会想在config.yml中这样做的。相反,您应该连接到内核请求并在那里设置连接。请查看这篇文章的公认答案:
然后,您可以在侦听器中使用$this->request->getHost(),解析子域,并在将子域的名称作为dbname参数传递后打开到数据库的连接。例如(未测试):
public function onKernelRequest()
{
// this might cause issues if there is no subdomain, might need regex...just an example
$dbname = array_shift(explode('.', $this->request->getHost()));
$params = $this->connection->getParams();
if ($dbname !== $params['dbname'])
{
$this->connection->close();
$this->connection = new Connection()
$params,
$this->connection->getDriver(),
$this->connection->getConfiguration(),
$this->connection->getEventManager()
);
try {
$this->connection->connect();
} catch (Exception $e) {
// log and handle exception
}
}
}https://stackoverflow.com/questions/27469800
复制相似问题