我想在页面的页脚添加一个小统计数据,大概是'184ms/6/10ms‘。
其中,184ms是页面生成时间,6是查询计数,10是数据库查询所用的时间。
我可以计算出页面生成时间,但是如何从理论上获得数据库统计数据呢?
当然,这是在应用程序环境中运行时,我很欣赏在app_dev中,可能有一种方法可以在symfony profiler运行时访问它。
任何帮助都将不胜感激。
发布于 2015-03-17 19:07:52
您可以使用DebugStack对象来完成此操作。
您将拥有一个包含每个查询及其各自执行时间的数组。
示例:
$doctrine = $this->get('doctrine');
$doctrineConnection = $doctrine->getConnection();
$stack = new \Doctrine\DBAL\Logging\DebugStack();
$doctrineConnection->getConfiguration()->setSQLLogger($stack);
$em = $doctrine->getManager();
... // Perform query
var_dump($stack);$stack的Var转储示例:
Doctrine\DBAL\Logging\DebugStack Object
(
[queries] => Array
(
[1] => Array
(
[sql] => SELECT t0.id AS id1 FROM Test t0
[params] => Array
(
)
[types] => Array
(
)
[executionMS] => 0.00018191337585449
)
[2] => Array
(
[sql] => SELECT t0.id AS id1 FROM Test t0
[params] => Array
(
)
[types] => Array
(
)
[executionMS] => 0.00016307830810547
)
)
[enabled] => 1
[start] => 1426590420.2278
[currentQuery] => 2
)发布于 2016-12-27 04:27:42
首先,在您的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 main模板中使用它,如下所示:
{{ query_count() }}、{{ query_time() }}、{{ request_time() }}
记住:
如果您将{{ query_count() }}或{{ query_time() }}放在模板的开头,it 将不会显示所有查询。
最佳实践是将它们放在主模板的末尾。如果您想在开始时显示它们,请使用CSS。
https://stackoverflow.com/questions/29096343
复制相似问题