【发布时间】:2013-10-16 14:49:55
【问题描述】:
我正在使用 symfony2 创建一个 SaaS,提供私人网站。 我想做的是让人们以这种方式访问网站:
http://www.mydomain.com/w/{website_name}
这是我正在使用的路由配置:
websites:
resource: "@MyBundle/Resources/config/routing.yml"
prefix: /w/{website_name}
问题是当我尝试访问时,例如,http://www.mydomain.com/w/chucknorris 我收到错误:
在渲染模板期间引发了异常(“一些 缺少强制参数(“website_name”)来生成 URL 对于路线“websites_homepage”。”)在 "MyBundle:Publication:publicationsList.html.twig"。
我的理解是我的路由配置运行良好,但是当我调用路由器在网站中生成 url 时,它不知道“context”{website_name} url 参数。
我设想的一个解决方案是找到一种方法,当它在上下文中设置时自动、无缝地注入此参数。
到目前为止我所能做的就是创建一个服务来以这种方式获取此参数:
public function __construct(Registry $doctrine, ContainerInterface $container) {
$website_name = $container->get('request')->get("website_name");
if (!empty($website_name)) {
$repository = $doctrine->getManager()->getRepository('MyBundle:website');
$website = $repository->findOneByDomain($website_name);
if ($website) {
$this->website = $website;
} else {
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
}
} else {
$this->isPortal = true;
}
}
我的问题是:如何将该参数注入所有生成的 url 以避免参数丢失的错误,并且每次我在控制器或树枝中调用路由器时都不必手动指定它? (我想这是关于请求事件的事情,但我不知道如何去做,特别是如何根据 symfony2 的良好用法来做)
更新 这是我基于 symfony 提供的 locallistener 创建的监听器:
<?php
class WebsiteNameRouteEventListener implements EventSubscriberInterface {
private $router;
public function __construct(RequestContextAwareInterface $router = null) {
$this->router = $router;
}
public function onKernelResponse(FilterResponseEvent $event) {
$request = $event->getRequest();
$this->setWebsiteName($request);
}
public function onKernelRequest(GetResponseEvent $event) {
$request = $event->getRequest();
$this->setWebsiteName($request);
}
public static function getSubscribedEvents() {
return array(
// must be registered after the Router to have access to the _locale
KernelEvents::REQUEST => array(array('onKernelRequest', 16)),
KernelEvents::RESPONSE => 'onKernelResponse',
);
}
private function setWebsiteName(Request $request) {
if (null !== $this->router) {
echo "NEW CODE IN ACTION";die();
$this->router->getContext()->setParameter('website_name', $request->attributes->get("website_name"));
}
}
}
但我仍然收到此错误:
在渲染模板期间引发了异常(“一些 缺少强制参数(“website_name”)来生成 URL 对于路线“主页”。”)在 “MyBundle:出版物:publicationsList.html.twig”。 500 内部 服务器错误 - Twig_Error_Runtime 1 链接异常:
MissingMandatoryParametersException »
没有我的回声“....”; die() 正在执行,所以我猜 twig 在执行路径(路由名称)代码时没有触发我正在监听的事件。
有什么想法吗?
【问题讨论】:
标签: php symfony url-routing