[英]Dynamic route prefix in Symfony2
我正在使用提供私人網站的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時,出現錯誤:
在呈現模板時,“ MyBundle:Publication:publicationsList.html.twig”中引發了一個異常(“缺少某些必需參數(“ website_name”)以生成路線“ websites_homepage”的URL。”
據我了解 ,我的路由配置運行良好,但是當我調用路由器在網站中生成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"));
}
}
}
但是我仍然收到此錯誤:
在呈現模板期間,“ MyBundle:Publication:publicationsList.html.twig”中引發了一個異常(“缺少某些強制性參數(“ website_name”)以生成路線“ home”的URL。“)。 500內部服務器錯誤-Twig_Error_Runtime 1鏈接的異常:
MissingMandatoryParametersException »
沒有我的回聲“ ....”; die()正在執行,因此我猜它在執行path(routename)代碼時不會觸發我正在監聽的事件。
任何想法 ?
您可以使用路由器上下文。
$this->router->getContext()->setParameter('website_name', $website_name);
看到這個文件: https : //github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpKernel/EventListener/LocaleListener.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.