如何在事件侦听器中触发重定向到特定路由器?
有很多例子,但我找不到一个“GetResponseForExceptionEvent”。例如,当我通过@roter
作为参数时$this->router....
似乎没有这样做。
我检查了这些,但我可能错过了一些东西:
service.yml
services:
kernel.listener.kernel_request:
class: Booking\AdminBundle\EventListener\ErrorRedirect
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
事件监听器:
namespace Booking\AdminBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ErrorRedirect
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
// redirect to '/' router or '/error'
//$event->setResponse(...........);
}
}
}
答案 0 :(得分:37)
您有两个选择:
如果有效,请告诉我。
注意:查看Symfony2 redirect for event listener
1 将路由器传递给您的事件监听器:
kernel.listener.kernel_request:
class: Booking\AdminBundle\EventListener\ErrorRedirect
arguments:
router: "@router"
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
2 使用侦听器中的路由器重定向用户:
namespace Booking\AdminBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
class ErrorRedirect
{
/**
* Holds Symfony2 router
*
*@var Router
*/
protected $router;
/**
* @param Router
*/
public function __construct(Router $router)
{
$this->router = $router;
}
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
/** Choose your router here */
$route = 'route_name';
if ($route === $event->getRequest()->get('_route')) {
return;
}
$url = $this->router->generate($route);
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
}
您可以创建一条特殊路线,以匹配所有不存在的路线;然后,您可以在您选择的控制器中按照您想要的方式处理重定向,这里是PageNotFoundController:
1 在app / config / routing.yml的末尾
pageNotFound:
pattern: /{path}
defaults: { _controller: AcmeDemoBundle:PageNotFound:pageNotFound, path: '' }
requirements:
path: .*
2
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class PageNotFoundController extends Controller
{
public function pageNotFoundAction()
{
// redirect the way you want
}
}