You have 2 options:
- Use an Event Listener
- Use a route that matches all the routes that don't exist and trigger an action in a controller.
Let me know if that works.
Option 1
Note: Have a look at Symfony2 redirect for event listener
1 Pass the router to your event listener:
kernel.listener.kernel_request:
class: BookingAdminBundleEventListenerErrorRedirect
arguments:
router: "@router"
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
2 Use the router within the listener to redirect users:
namespace BookingAdminBundleEventListener;
use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
use SymfonyComponentHttpFoundationRedirectResponse;
use SymfonyBundleFrameworkBundleRoutingRouter;
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);
}
}
}
Option 2
You can create a special route that will match all routes that don't exist; You can then handle the redirect the way you want within the controller of your choice, here PageNotFoundController:
1 At the end of app/config/routing.yml
pageNotFound:
pattern: /{path}
defaults: { _controller: AcmeDemoBundle:PageNotFound:pageNotFound, path: '' }
requirements:
path: .*
2
<?php
namespace AcmeDemoBundleController;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
class PageNotFoundController extends Controller
{
public function pageNotFoundAction()
{
// redirect the way you want
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…