Home » Php » php – Symfony2 redirect for event listener?

php – Symfony2 redirect for event listener?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a kernel event listener setup (kernel.controller) to redirect the user if hes not logged in. The event listener is succefully getting called, however im having trouble figuring out how to redirect. Here’s what i got:

$cont = $event->getController('testpost');
$event->setResponse($cont);

Which gives me the error:

Fatal error: Call to undefined method Symfony\Component\HttpKernel\Event\FilterControllerEvent::setResponse() 
How to&Answers:

You can’t set a response to a FilterControllerEvent object. You need to listen for the kernel.request event because its GetResponseEvent object has the setResponse() method:

$route = 'route_name';

if ($route === $event->getRequest()->get('_route')) {
    return;
}

$url = $this->router->generate($route);
$response = new RedirectResponse($url);
$event->setResponse($response);

Answer:

If you wanna redirect from FilterControllerEvent you should use this one:

public function onKernelController(FilterControllerEvent $event)
{
    // do something
    $event->setController(function() use ($redirectUrl) {
        return new RedirectResponse($redirectUrl);
    });
}

Answer:

More ore less clear way to redirect on ‘kernel.controller’ event

public function onKernelController(FilterControllerEvent $event)
{
    /* @var $controller \Symfony\Bundle\FrameworkBundle\Controller\Controller */
    $controller = $event->getController()[0]; // PHP 5.4 or $controller = $controller[0];

    throw new HttpException(307, null, null, array('Location' => $controller->generateUrl('homepage')));
}

Answer:

Here is a similar question about doing (almost) the same thing. It should give you a clue.

Symfony 2 – redirect if the user is logged in

Hope it helps.

Answer:

This ain’t no way to go, my friend. You should use a default Symfony Security to cover that for you…