Symfony 4 : ignore kernel events coming from debug toolbar

廉价感情. 提交于 2019-12-01 09:12:27

问题


I'm quite new to Symfony so forgive me if it seems obvious for you :)

For my project, i need to perform some actions depending on the url. I use kernel events, more specifically the kernel request to do so.

In services.yaml :

App\Service\UrlManager:
    tags:
        - { name: kernel.event_listener, event: kernel.request}  

In UrlManager.php :

public function onKernelRequest(GetResponseEvent $event)
{
    $request = Request::createFromGlobals();
    $hostname = parse_url($request->server->get('HTTP_HOST'),PHP_URL_HOST);

    /*
     * here my treatment that works fine :)
     */ 

But as i'm in DEV mode, the same event is fired again by the debug toolbar... The only workaround i found was by adding this before my treatment :

if (substr($request->server->get('REQUEST_URI'),0,6) != '/_wdt/') {

Also works fine, but i think it's not the best thing to do, because something very specific will stay in the project, and only for DEV mode. Is there a way to "tell" the toolbar not to fire this event ? Maybe something to add in services.yaml ? Or some other config parameter ?


回答1:


So I did a bit more research. It's not that the kernel event is being fired twice but rather that once your original page is sent to the browser a bit of javascript initiates a second _wdt request for additional information. So you actually have two independent requests. You can see this by pressing F12 in your browser and then selecting the network tab and refreshing.

It is easy enough to filter the debug request since the name of the route will always be _wdt. And you can also get the host directly from the request. Still want to check for the master request because eventually your code might trigger sub requests.

public function onRequest(GetResponseEvent $event)
{
    // Only master
    if (!$event->isMasterRequest()) {
        return;
    }
    $request = $event->getRequest();

    // Ignore toolbar
    if ($request->attributes->get('_route') === '_wdt') {
        return;
    }

    // Avoid parsing urls and other stuff, the request object should have
    // all the info you need
    $host = $request->getHost();

}


来源:https://stackoverflow.com/questions/48074428/symfony-4-ignore-kernel-events-coming-from-debug-toolbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!