无法覆盖Symfony 2请求中的pathInfo [英] Unable to overwrite pathInfo in a Symfony 2 Request
问题描述
我正在尝试处理别名(友好网址),可能我做的不正确。我想做的就是将 / blog / my-post-about-something之类的网址转换为 / posts / 23。
I'm trying to deal with aliases (friendly-urls) and probably I'm not doing it right. What I want to do is to transform urls like '/blog/my-post-about-something' into '/posts/23'.
我写了一个侦听器对于进行一些操作并修改原始请求的kernel.request事件
I have written a listener for the kernel.request event that makes some operations and modifies the original request
class RequestListener
{
public function onKernelRequest(KernelEvent $event)
{
$request = $event->getRequest();
$converted_path = $this->getPathIfAny($request);
if ($converted_path) {
$request->server->set('REQUEST_URI', $converted_path);
}
}
public function getPathIfAny(Request $request)
{
return $somePathOrNull;
}
}
所有逻辑均正常运行并更新原始请求。问题是,即使我更改了 REQUEST_URI,属性$ pathInfo仍然保持不变并指向先前的路径,因此我不断收到404错误。
All the logic works properly and updates the original request. The problem is, even if I change the 'REQUEST_URI', the property $pathInfo remains unaltered and pointing to the previous path, so I keep getting 404 errors.
有什么方法可以完全覆盖uri,还是应该尝试以其他方式解决问题?
Is there any way to override the uri completely, or should I try to solve the problem in a different manner?
这里是侦听器的定义
my_cmf.request_listener:
class: My\CMFBundle\Event\RequestListener
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest , priority: -10}
相关链接此问题: https://github.com/symfony/symfony/issues/10478
推荐答案
我的项目有类似的问题。我能够更新路径信息,但仍然很难将其传递给后续事件
I have a similar issue with my project. I was able to update the path info, but still struggling to get it passed to subsequent events
尝试一下:
$event->getRequest()->server->set('REQUEST_URI', '/en/guestbook');
$event->getRequest()->initialize($event->getRequest()->query->all(), $event->getRequest()->request->all(), $event->getRequest()->attributes->all(), $event->getRequest()->cookies->all(), $event->getRequest()->files->all(), $event->getRequest()->server->all(), $event->getRequest()->getContent());
var_dump($event->getRequest()->getPathInfo());
initialize方法将重置整个类。
The initialize method resets the whole class.
这篇关于无法覆盖Symfony 2请求中的pathInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!