2013-04-03 26 views
3

我的路由定義是這樣的:如何使用路由不使用GET參數進行重定向?

# New URLs 
article_show: 
    pattern: /article/{id} 
    defaults: { _controller: AcmeDemoBundle:Article:show } 

# Old URLs 
article_show_legacy: 
    path:   /article-{id}-{param}.html 
    requirements: 
     param: foo|bar 
    defaults: 
     _controller: FrameworkBundle:Redirect:redirect 
     route:  article_show 
     permanent: true 

我想知道我怎麼可以重定向到article_show_legacy沒有article_show參數param。此刻,無論何時訪問/article-1-foo.html(例如),我都會重定向到/article/1?param=foo。我想放棄?param=foo,所以我被重定向到/article/1

我知道我可以爲foo創建一條路線,爲bar創建一條路線,但在我的情況下,會有更多的案例。

我必須編寫自己的重定向控制器嗎?

+0

我通常如何處理這個業務邏輯在我的控制器或樹枝,你想要一個只配置型的解決方案,或者我應該張貼的響應類型? – Lighthart

+0

我知道我可以在控制器中處理這個問題,但我想知道路由組件是否提供了一些能夠自動處理的東西。 – iamdto

回答

0

你必須編寫自己的重定向控制器,或者在任何現有的控制器中創建重定向方法。

檢查redirect行動的RedirectController../vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php莫爾細節。

一些例子(我添加第三個選項stripAttributes):

public function redirectAction($route, $permanent = false, $stripAttributes = false) 
{ 
    if ('' == $route) { 
     return new Response(null, $permanent ? 410 : 404); 
    } 

    $attributes = array(); 
    if (!$stripAttributes) { 
     $attributes = $this->container->get('request')->attributes->get('_route_params'); 
     unset($attributes['route'], 
       $attributes['permanent'], 
       $attributes['stripAttributes']); 
    } 

    return new RedirectResponse($this->container->get('router')->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $permanent ? 301 : 302); 
} 
+0

太棒了!我只是做了類似的事情,並使用'array'作爲第三個參數。 – iamdto

相關問題