Symfony2: connect to NotFoundHttpException to redirect

I am currently porting our project to symfony2. In our current code base, we have a mechanism that allows us to define routes in the database table. Basically we specify the regular expression with which the request URL is mapped, and specify the URL to which the user should be redirected. This redirect works like a "last resort" right before you drop 404. Thus, these redirects never rewrite URLs that correspond to existing actions, and the match is done lazily only if 404 were selected.

Is there a way to hook into the Symfony event model and listen to NotFoundHttpException do just that (for example, issue a 301/302 redirect if the URL matches some regular expression instead of skipping the 404th bend)?

0
source share
1 answer

As you can see from this cookbook page , the kernel.exception event is fired whenever an exception is thrown. I donโ€™t know that there is a specific event for the NotFoundHttpException exception, but I would suggest creating my own listener service for all exceptions, and then check the type of exception inside the service and add your own logic.

(Note: I have not tested this, but it should at least give you an idea of โ€‹โ€‹how this can be achieved.)

Configuration

acme.exception_listener: class: Acme\Bundle\AcmeBundle\Listener\RedirectExceptionListener arguments: [@doctrine.orm.entity_manager, @logger] tags: - { name: kernel.event_listener, event: kernel.exception, method: checkRedirect } 

Listener Service

 namespace Acme\Bundle\AcmeBundle\Listener; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\Log\LoggerInterface; use Doctrine\ORM\EntityManager; class RedirectExceptionListener { /** * @var \Doctrine\ORM\EntityManager */ protected $em; protected $logger; function __construct(EntityManager $em, LoggerInterface $logger) { $this->em = $em; $this->logger = $logger; } /** * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event */ public function checkRedirect(GetResponseForExceptionEvent $event) { $exception = $event->getException(); if ($exception instanceof NotFoundHttpException) { // Look for a redirect based on requested URI // eg... $uri = $event->getRequest()->getUri(); $redirect = $this->em->getRepository('AcmeBundle:Redirect')->findByUri($uri); if (!is_null($redirect)) { $event->setResponse(new RedirectResponse($redirect->getUri())); } } } } 
+4
source

Source: https://habr.com/ru/post/1205087/


All Articles