Symfony2:在页面加载事件监听器中获取路由 [英] Symfony2: Getting Route in Page Load Event Listener
问题描述
如何在页面加载甚至侦听器中获取路由?
How can I get the route in a page load even listener?
在services.yml中有以下代码:
I have the following code in services.yml:
page_load_listener:
class: Acme\MainBundle\EventListener\PageLoadListener
arguments: [@security.context, @session]
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController, priority: 64 }
在PageLoadListener类中,我有相应的方法:
In the PageLoadListener class I have the corresponding method:
public function onKernelController(FilterControllerEvent $event)
{
// Some code I need to execute that needs the route arguments
}
问题似乎是路由和参数不可用.我想念什么?
The problem seems to be that the route and arguments are not available. What am I missing?
我需要通过哪个事件来选择路线及其参数?
谢谢
JB
推荐答案
All kernel events extend KernelEvent
, which means you can simply acess the Request
object via $event->getRequest()
.
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
// Matched route
$_route = $request->attributes->get('_route');
// Matched controller
$_controller = $request->attributes->get('_controller');
// All route parameters including the `_controller`
$params = $request->attributes->get('_route_params');
}
如果您想获得普通的路线属性,只需过滤掉所有以"_"开头的元素.
If you'd like to get plain route attributes, simply filter out all the elements prefixed with "_".
选择适当的事件进行监听取决于您的特定用例.
Choosing the proper event to listen to depends on your specific use case.
这篇关于Symfony2:在页面加载事件监听器中获取路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!