php Symfony2 重定向事件侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12916439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:28:16  来源:igfitidea点击:

Symfony2 redirect for event listener?

phpsymfony

提问by Jonah Katz

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:

我有一个内核事件监听器设置 (kernel.controller) 来重定向用户,如果他没有登录。事件监听器被成功调用,但是我无法弄清楚如何重定向。这是我得到的:

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

Which gives me the error:

这给了我错误:

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

回答by NHG

If you wanna redirect from FilterControllerEventyou should use this one:

如果你想重定向,FilterControllerEvent你应该使用这个:

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

回答by Elnur Abdurrakhimov

You can't set a response to a FilterControllerEventobject. You need to listen for the kernel.requestevent because its GetResponseEventobject has the setResponse()method:

您无法设置对FilterControllerEvent对象的响应。您需要侦听该kernel.request事件,因为它的GetResponseEvent对象具有以下setResponse()方法:

$route = 'route_name';

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

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

回答by 66Ton99

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

更多或不太清楚的重定向“kernel.controller”事件的方法

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')));
}

回答by Juan Sosa

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

Symfony 2 - 如果用户登录则重定向

Hope it helps.

希望能帮助到你。

回答by thorinkor

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

这不是没有办法,我的朋友。您应该使用默认的 Symfony Security 来为您覆盖...