我们有一个使用 symfony 1.4 框架开发的网站。该网站应该能够拥有多个域。每个域都有其特殊的主页和其他一切。实际上,域必须是每个操作的这样一个参数,根据它,操作从数据库获取数据并显示它。
例如,我们有一个关于我们的页面。我们将关于我们的内容保存在about_us表中。该表有一个 website_id。我们将网站信息保存在网站表中。假设这样:
website (id, title, domain)
about_us (id, content, website_id)
网站内容:
(1, 'foo', 'http://www.foo.com') and (2, 'bar', 'http://www.bar.com')
关于我们内容:
(1, 'some foo', 1) and (2, 'some bar', 2)
问题是,我应该如何配置我的 Symfony 项目才能做到这一点?获取域作为参数并在 Symfony 操作中使用它?
您可以创建自己的扩展 sfRoute 的路由类。该路由将为所有请求添加“domain”参数:
//apps/frontend/lib/routing/myroute.class.php
class myRoute extends sfRoute
{
public function matchesUrl($url, $context = array())
{
// first check if it is a valid route:
if (false === $parameters = parent::matchesUrl($url, $context))
{
return false;
}
$domain = $context['host'];
// add the $domain parameter:
return array_merge(array(
'domain' => $domain
), $parameters);
}
}
Routing.yml(示例):
default_module:
class: myRoute
url: /:module/:action/:id
...
在您的操作中,您将获得域名:
$request->getParameter('domain');
有很多方法可以做到这一点。 您可以扩展 sfFrontWebController,并在dispatch() 方法中添加额外的代码。
# app/myapp/config/factories.yml
all:
controller:
class: myController
// lib/myController.class.php
class myController extends sfFrontWebController
{
public function dispatch()
{
$selectedSite = SiteTable::retrieveByDomain($_SERVER['HTTP_HOST']); // Example
if (!$selectedSite) {
throw new sfException('Website not found');
}
// Store any site value in parameter
$this->context->getRequest()->setParameter('site_id',$selectedSite->getId());
parent::dispatch();
}
}