首先在您的 config.yml 中启用学说分析
doctrine:
dbal:
...
profiling: true
像这样创建 Twig 扩展类:
<?php
// src/AppBundle/Twig/AppExtension.pgp
namespace AppBundle\Twig;
use Doctrine\DBAL\Logging\DebugStack;
class AppExtension extends \Twig_Extension
{
/**
* @var DebugStack
*/
protected $debugStack;
/**
* AppExtension constructor.
* @param DebugStack $debugStack
*/
function __construct(DebugStack $debugStack)
{
$this->debugStack = $debugStack;
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('request_time', [$this, 'requestTime'], ['is_safe' => ['html']]),
new \Twig_SimpleFunction('query_time', [$this, 'queryTime'], ['is_safe' => ['html']]),
new \Twig_SimpleFunction('query_count', [$this, 'queryCount'], ['is_safe' => ['html']]),
];
}
/**
* Returns application execution time
*
* @param int $decimals
* @return string
*/
public function requestTime($decimals = 0)
{
return number_format((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'])*1000, $decimals);
}
/**
* Returns doctrine query execution time
*
* @param int $decimals
* @return string
*/
public function queryTime($decimals = 2)
{
return number_format(array_sum(array_column($this->debugStack->queries, 'executionMS'))*1000, $decimals);
}
/**
* Returns doctrine query count
*
* @return string
*/
public function queryCount()
{
return count($this->debugStack->queries);
}
}
在services.yml注册您的分机
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
arguments: ["@doctrine.dbal.logger.profiling.default"]
public: false
tags:
- { name: twig.extension }
在twig主模板中使用如下:
{{ query_count() }}、{{ query_time() }}、{{ request_time() }}
记住:
如果您将{{ query_count() }} 或{{ query_time() }} 放在模板的开头,它不会显示所有查询。
最佳做法是将它们放在主模板的末尾。如果您想在一开始就显示它们,请使用 CSS。
现场演示: https://mysql-todolist.tk