php - Symfony2 : Getting Route in Page Load Event Listener

标签 php symfony

如何在页面加载甚至监听器中获取路由?

我在 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 类中我有相应的方法:

    public function onKernelController(FilterControllerEvent $event)
    {

        // Some code I need to execute that needs the route arguments

    }

问题似乎是路由和参数不可用。我错过了什么?

我需要传递哪个事件来获取路由及其参数?

谢谢,

JB

最佳答案

所有内核事件扩展 KernelEvent ,这意味着您可以通过 $event->getRequest() 简单地访问 Request 对象。

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');
}

如果您想获得普通的路由属性,只需过滤掉所有以“_”为前缀的元素即可。

根据您的具体用例选择合适的事件来监听。

关于php - Symfony2 : Getting Route in Page Load Event Listener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11505287/

相关文章:

php - 在 PHP 中组合目录和文件名(相当于 .Net 中的 Path.Combine)

php - wp_options 的 option_value 太长

php - 组合 2 个查询来获取属于我的 friend 且具有特定名称的用户

symfony - 使用 Symfony2 实现工厂模式的最佳实践

php - 如何使用 Twig 的 Intl 扩展提高百分比格式的小数精度?

symfony - Doctrine - 如何初始化 DB 值

php - 如何在 laravel blade 的 for-loop 中设置值

php - jQGrid 与 jquery 工具提示工具

php - 根据实体属性值查询所有对象?

php - Symfony 2/Doctrine 2 : Two Entities for the same table, 用一个代替另一个