drzb7969753 2012-11-26 12:02
浏览 47
已采纳

symfony2:挂钩到NotFoundHttpException以进行重定向

I'm currently migrating our project to symfony2. In our current codebase, we have a mechanism that allows us to define routings in a database table. We basically specify a regex the request URL gets matched against, and specify the URL the user should be redirected to. This redirecting works as a "last resort" right before throwing the 404. That way, these redirects never overwrite URLs that match existing actions and the matching is done lazily, only in case a 404 would have been thrown.

Is there a way to hook into Symfony's event model and listen for the NotFoundHttpException to do exactly that (e.g. issuing a 301/302 redirect if the URL matches some regex, instead of letting the 404 trough)?

  • 写回答

1条回答 默认 最新

  • dtfo55908 2012-11-26 12:24
    关注

    As you can see from this cookbook page, a "kernel.exception" event is fired whenever an exception is thrown. I'm not aware of there being a specific event for a NotFoundHttpException but I'd suggest creating your own listener service for all exceptions and then checking within the service for the type of exception and adding your custom logic.

    (Note: I haven't 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
                // e.g....
                $uri = $event->getRequest()->getUri();
                $redirect = $this->em->getRepository('AcmeBundle:Redirect')->findByUri($uri);
                if (!is_null($redirect)) {
                    $event->setResponse(new RedirectResponse($redirect->getUri()));
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路