1

I'm working with Symfony 2.1. I want to setup a redirect routine depending on User is logged in or not. The way I check it is $User->isLoggedIn() where User is a service.

I want to do this before a controller executes. I have few other things happening just before Controller executes. I use event: kernel.controller of kernel.event_listener to do those things. But I realized that I can not redirect to a URL using this event.

I understand I need to use event: kernel.request of kernel.event_listener to be able to redirect to a URL.

Problem. I use the following logic to figure out whether I need to redirect or not.

if (!$controller[0] instanceof NoLogInNeededInterface) {

     if (!$User->isLoggedIn()) {
        //redirect here
     }
}

So, in the kernel.request event, $controler[0] is not available. In the kernel.controller event, response can't be set (will be ignored).

Has anyone got same problem and solved. Or is there any better way of doing, what I'm trying to do?

4

1 回答 1

1

我意识到我想要的可以通过使用 kernel.event_listner 的 kernel.exception 事件来实现。

所以在服务中:

my.service:
   class: MyBundle\EventListner\ExceptionListner
        tags:
           - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
        arguments: [ %logoutUrl% ]

然后在类本身:

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ExceptionListner
{
    protected $_url;

    public function __construct($url)
    {
        $this->_url = $url;
    }

    public function onKernelException(GetResponseForExceptionEvent $event) {
        $exception = $event->getException();
        //dont necessarily need this condition
        if ($exception instanceof RedirectException) {
            $response = new RedirectResponse($this->_url);
            $event->setResponse($response);
        }
    }

}

我仍然接受建议,如果这是或不是更好的方法。希望这也能帮助正在苦苦挣扎的人。磷

于 2013-03-18T22:45:59.557 回答