Symfony 4:忽略来自调试工具栏的内核事件 [英] Symfony 4 : ignore kernel events coming from debug toolbar

查看:93
本文介绍了Symfony 4:忽略来自调试工具栏的内核事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Symfony还是很陌生,所以如果您觉得它很明显,请原谅我:)

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

对于我的项目,我需要根据URL执行一些操作。我使用内核事件,更具体地说是内核请求。

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.

在services.yaml中:

In services.yaml :

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

在UrlManager.php中:

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 :)
     */ 

但是当我处于DEV模式时,调试工具栏会再次触发相同的事件...
我发现的唯一解决方法是在治疗之前添加此方法:

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/') {

也可以,但是我认为这不是最好的做法,因为有些事情非常具体的内容将保留在项目中,并且仅用于DEV模式。
是否可以告诉工具栏不触发此事件?也许要在services.yaml中添加一些内容?还是其他一些配置参数?

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 ?

推荐答案

所以我做了更多的研究。并不是内核事件被触发两次,而是一旦您的原始页面发送到浏览器后,一小段javascript就会启动另一个_wdt请求以获取其他信息。因此,您实际上有两个独立的请求。您可以通过在浏览器中按F12键,然后选择网络选项卡并刷新来查看此内容。

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.

由于路由名称会永远是_wdt。您还可以直接从请求中获取主机。仍然要检查主请求,因为最终您的代码可能会触发子请求。

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();

}

这篇关于Symfony 4:忽略来自调试工具栏的内核事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆