syl*_*ain 3 php debugging events symfony symfony4
我对 Symfony 很陌生,所以如果这对你来说很明显,请原谅我:)
对于我的项目,我需要根据 url 执行一些操作。我使用内核事件,更具体地说是内核请求这样做。
在 services.yaml 中:
App\Service\UrlManager:
tags:
- { name: kernel.event_listener, event: kernel.request}
Run Code Online (Sandbox Code Playgroud)
在 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 :)
*/
Run Code Online (Sandbox Code Playgroud)
但是当我处于 DEV 模式时,调试工具栏再次触发了相同的事件......我发现的唯一解决方法是在我的治疗之前添加它:
if (substr($request->server->get('REQUEST_URI'),0,6) != '/_wdt/') {
Run Code Online (Sandbox Code Playgroud)
也可以正常工作,但我认为这不是最好的做法,因为某些非常具体的内容将保留在项目中,并且仅适用于 DEV 模式。有没有办法“告诉”工具栏不要触发这个事件?也许可以在 services.yaml 中添加一些内容?或者其他一些配置参数?
所以我做了更多的研究。并不是内核事件被触发两次,而是一旦您的原始页面被发送到浏览器,一些 javascript 就会启动第二个 _wdt 请求以获取附加信息。所以你实际上有两个独立的请求。您可以通过在浏览器中按 F12,然后选择网络选项卡并刷新来查看这一点。
过滤调试请求很容易,因为路由的名称将始终是 _wdt。而且你也可以直接从请求中获取主机。仍然要检查主请求,因为最终您的代码可能会触发子请求。
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();
}
Run Code Online (Sandbox Code Playgroud)