Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 redirect for event listener?

Tags:

php

symfony

I have a kernel event listener setup (kernel.controller) to redirect the user if he's not logged in. The event listener is succesfully getting called, however I'm 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()  
like image 732
Jonah Katz Avatar asked Oct 16 '12 14:10

Jonah Katz


2 Answers

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);     }); } 
like image 174
NHG Avatar answered Oct 22 '22 03:10

NHG


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); 
like image 38
Elnur Abdurrakhimov Avatar answered Oct 22 '22 01:10

Elnur Abdurrakhimov