2014-02-05 46 views
0

我想在特定的sutiation中在構造函數中進行重定向。 我試圖做這樣的:symfony2在構造函數中重定向

return new \Symfony\Component\HttpFoundation\RedirectResponse($url); 

像這樣:

return $this->redirect($url); 

但它不工作。在其他任何方法中,它都可以工作,但由於某些原因,此代碼在構造函數中不起作用。沒有錯誤或警告。

如果您需要更多信息請在評論中提問。 謝謝你的時間。

+3

在什麼構造函數中? –

+2

在構造函數中使用重定向的壞主意 –

+0

@MarkusKottländer: 在我的控制器的構造函數中。維克多:爲什麼這是一個壞主意? – gprusiiski

回答

1

在構造函數中使用重定向的壞主意。構造函數只返回當前的object of the class(在你的情況下控制器的對象),它不能返回redirect object。也許你可以解決你的任務路線,使用FrameworkBundle:Redirect:urlRedirect

# redirecting the root 
root: 
    path:/
    defaults: 
     _controller: FrameworkBundle:Redirect:urlRedirect 
     path: /app 
     permanent: true 

入住例子How to Configure a Redirect without a Custom Controller

+0

好的,但我怎麼能做出一個條件。例如,我有一個像「mysite.com/product」這樣的網址,如果例如$ this-> session-> get('some flag')訪問此網址爲false,則將其重定向到不同的網址或者它正確地繼續。 – gprusiiski

+0

它需要直接在控制器'action'中實現 –

+0

是的,但是我需要實現這個邏輯,而不是隻在一個地方執行這個邏輯(這就是爲什麼我想在構造函數中進行重定向的原因)。 我可以在防火牆和安全區域做到這一點,但這僅僅對我而言並不值得。 – gprusiiski

0

壞主意,從控制器直接重定向。我寧願拋出一些自定義異常。

class FooController{ 
    public function __construct(){ 
     if (some_test){ 
      throw RedirectionException(); // name it however you like 
     } 
    } 
} 

然後,在Symfony,設置了ExceptionListener將評估類型Exception拋出你的應用程序,重定向到另一個網址,如果必要的。此服務很可能取決於@routing服務來生成備用網址目標。

服務配置:

services: 
    kernel.listener.your_listener_name: 
     class: Your\Namespace\AcmeExceptionListener 
     tags: 
      - { name: kernel.event_listener, event: kernel.exception, method: onKernelException } 

Listener類:

class AcmeExceptionListener 
{ 
    public function onKernelException(GetResponseForExceptionEvent $event) 
    { 
     // You get the exception object from the received event 
     $exception = $event->getException(); 

     if ($exception instanceof RedirectionException){ 
      $response = new RedirectResponse(); 

      $event->setResponse($response); 
     } 
    } 
} 

這種方式可以保持單錯誤處理和重定向邏輯。太複雜?