【问题标题】:symfony2: hook into NotFoundHttpException for redirectionsymfony2:挂钩到 NotFoundHttpException 进行重定向
【发布时间】:2012-11-26 12:02:27
【问题描述】:
我目前正在将我们的项目迁移到 symfony2。在我们当前的代码库中,我们有一种机制允许我们在数据库表中定义路由。我们基本上指定了一个匹配请求 URL 的正则表达式,并指定用户应该被重定向到的 URL。这种重定向是在抛出 404 之前作为“最后的手段”。这样,这些重定向永远不会覆盖与现有操作匹配的 URL,并且匹配是延迟完成的,只有在抛出 404 的情况下。
有没有办法挂钩到 Symfony 的事件模型并监听 NotFoundHttpException 来做到这一点(例如,如果 URL 匹配某个正则表达式,则发出 301/302 重定向,而不是让 404 低谷)?
【问题讨论】:
标签:
php
symfony
url-routing
【解决方案1】:
正如您在this cookbook page 中看到的那样,只要抛出异常,就会触发“kernel.exception”事件。我不知道 NotFoundHttpException 存在特定事件,但我建议为所有异常创建自己的侦听器服务,然后在服务中检查异常类型并添加自定义逻辑。
(注意:我没有对此进行测试,但它至少应该让您了解如何实现这一点。)
配置
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 }
监听服务
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()));
}
}
}
}