程序员人生 网站导航

Zend Framework教程-Zend_Db-数据库操作7-Zend_Db_Profiler翻译

栏目:ZendFramework时间:2014-01-29 04:15:58

Zend_Db_Profiler

Introduction简介

Zend_Db_Profiler can be enabled to allow profiling of queries. 

Profiles include the queries processed by the adapter as well as elapsed time to run the queries, allowing inspection of the queries that have been performed without needing to add extra debugging code to classes. 

Advanced usage also allows the developer to filter which queries are profiled.

Enable the profiler by either passing a directive to the adapter constructor, or by asking the adapter to enable it later.

Zend_Db_Profiler可以启用查询分析功能。分析内容包括适配器处理的查询和查询的运行消耗时间。通过它,无需添加额外的调试代码,就可以检查已执行的查询。


$params = array(    'host'     => '127.0.0.1',    'username' => 'webuser',    'password' => 'xxxxxxxx',    'dbname'   => 'test'    'profiler' => true  // turn on profiler                        // set to false to disable (disabled by default)); $db = Zend_Db::factory('PDO_MYSQL', $params); // turn off profiler:$db->getProfiler()->setEnabled(false); // turn on profiler:$db->getProfiler()->setEnabled(true);



The value of the 'profiler' option is flexible. It is interpreted differently depending on its type. Most often, you should use a simple boolean value, but other types enable you to customize the profiler behavior.

A boolean argument sets the profiler to enabled if it is a TRUE value, or disabled if FALSE. The profiler class is the adapter's default profiler class,Zend_Db_Profiler.

启用分析功能,配置方法是非常灵活的。大多数情况下,你只需使用一个简单的布尔值,但允许使用其他自定义类型来启用分析功能。

如果参数设置为true表示启用分析功能。如果要禁用只需设置为false即可。Zend_Db_Profiler类是适配器的默认分析器类。

  1. $params['profiler'] =true;
  2. $db = Zend_Db::factory('PDO_MYSQL',$params);

An instance of a profiler object makes the adapter use that object. The object type must beZend_Db_Profiler or a subclass thereof. Enabling the profiler is done separately.

适配器使用分析器对象时。分析器对象的类型必须是 Zend_Db_Profiler 或者其子类。

  1. $profiler = MyProject_Db_Profiler();
  2. $profiler->setEnabled(true);
  3. $params['profiler'] =$profiler;
  4. $db = Zend_Db::factory('PDO_MYSQL',$params);

The argument can be an associative array containing any or all of the keys 'enabled', 'instance', and 'class'. 

The 'enabled' and 'instance' keys correspond to the boolean and instance types documented above. 

The 'class' key is used to name a class to use for a custom profiler. The class must beZend_Db_Profiler or a subclass. 

The class is instantiated with no constructor arguments. 

The 'class' option is ignored when the 'instance' option is supplied.


配置参数可以是一个关联数组。其键名为'enabled', 'instance', 和'class'. 

 'enabled' 和 'instance' 键的值是一个boolean值和profiler对象的实例

 'class'  指定自定义的分析器的类名。类必须是Zend_Db_Profiler或Zend_Db_Profiler的子类子类。实例化类时,无须传递构造参数。

 使用'instance'时, 'class'  选项会被忽略。


  1. $params['profiler'] =array(
  2.     'enabled' => true,
  3.     'class'   => 'MyProject_Db_Profiler'
  4. );
  5. $db = Zend_Db::factory('PDO_MYSQL',$params);


Finally, the argument can be an object of type Zend_Config containing properties, which are treated as the array keys described above. 

For example, a file "config.ini" might contain the following data:

上面的配置参数也可以使用Zend_Config实现。数组的key可以作为配置选项的名称。例如,一个“config.ini”文件可能包含以下数据:

  1. [main]
  2. db.profiler.class   = "MyProject_Db_Profiler"
  3. db.profiler.enabled = true


This configuration can be applied by the following PHP code:

使用这些配置的方法:

  1. $config = new Zend_Config_Ini('config.ini','main');
  2. $params['profiler'] =$config->db->profiler;
  3. $db = Zend_Db::factory('PDO_MYSQL',$params);


The 'instance' property may be used as in the following:

 'instance' 配置选项可以按照如下方法使用:

  1. $profiler = new MyProject_Db_Profiler();
  2. $profiler->setEnabled(true);
  3. $configData = array(
  4.     'instance' => $profiler
  5.     );
  6. $config = new Zend_Config($configData);
  7. $params['profiler'] =$config;
  8. $db = Zend_Db::factory('PDO_MYSQL',$params);

Using the Profiler

At any point, grab the profiler using the adapter's getProfiler() method:

在任何时候, 要使用分析器。都要通过适配器的 getProfiler()方法调用

  1. $profiler = $db->getProfiler();

This returns a Zend_Db_Profiler object instance. With that instance, the developer can examine your queries using a variety of methods:

得到一个Zend_Db_Profiler 对象实例后,开发人员可以使用如下方法进行查询语句的分析工作:

  • getTotalNumQueries() returns the total number of queries that have been profiled. 返回查询语句的个数

  • getTotalElapsedSecs() returns the total number of seconds elapsed for all profiled queries. 返回所有查询语句消耗的时间

  • getQueryProfiles() returns an array of all query profiles. 返回所有查询语句

  • getLastQueryProfile() returns the last (most recent) query profile, regardless of whether or not the query has finished (if it hasn't, the end time will beNULL)  无论查询是否完成,都会返回最后一个(最近一个)查询信息,(如果没有的话,返回NULL)

  • clear() clears any past query profiles from the stack.  从堆栈中清除以往任何查询信息。

The return value of getLastQueryProfile() and the individual elements ofgetQueryProfiles() are Zend_Db_Profiler_Query objects, which provide the ability to inspect the individual queries themselves:

 getLastQueryProfile() ,getQueryProfiles() 的返回值 是 Zend_Db_Profiler_Query 对象。还提供检查个别的查询的方法:

  • getQuery()   returns the SQL text of the query. The SQL text of a prepared statement with parameters is the text at the time the query was prepared, so it contains parameter placeholders, not the values used when the statement is executed.

    返回SQL语句。 SQL语句是预处理statement 的语句,所以它包含参数占位符,而不是具体执行的语句。

  • getQueryParams() returns an array of parameter values used when executing a prepared query. This includes both bound parameters and arguments to the statement'sexecute() method. The keys of the array are the positional (1-based) or named (string) parameter indices.

    返回一个数组,包含预处理查询执行时使用的参数值。 包括绑定参数和statement的execute() 方法的参数。数组的key是位置(索引从1开始)或者名称(字符串)参数索引

  • getElapsedSecs() returns the number of seconds the query ran. 返回查询运行的秒数。


The information Zend_Db_Profiler provides is useful for profiling bottlenecks in applications, and for debugging queries that have been run. 

For instance, to see the exact query that was last run:

Zend_Db_Profiler提供信息对分析应用程序中的瓶颈非常有用的,也可以调试运行的查询。例如,获取最后一次运行的查询:

  1. $query = $profiler->getLastQueryProfile();
  2.  
  3. echo$query->getQuery();

Perhaps a page is generating slowly;

use the profiler to determine first the total number of seconds of all queries, and then step through the queries to find the one that ran longest:

如果一个页面加载运行缓慢。可以使用Profiler来确定所有查询的消耗时间总数,然后逐步找到一个运行时间最长的查询:

  1. $totalTime    = $profiler->getTotalElapsedSecs();
  2. $queryCount   = $profiler->getTotalNumQueries();
  3. $longestTime  = 0;
  4. $longestQuery = null;
  5.  
  6. foreach ($profiler->getQueryProfiles()as $query){
  7.     if ($query->getElapsedSecs() >$longestTime){
  8.         $longestTime  = $query->getElapsedSecs();
  9.         $longestQuery = $query->getQuery();
  10.     }
  11. }
  12.  
  13. echo'Executed ' . $queryCount .' queries in ' . $totalTime .
  14.      ' seconds' . "";
  15. echo'Average query length: ' . $totalTime / $queryCount .
  16.      ' seconds' . "";
  17. echo'Queries per second: ' . $queryCount / $totalTime . "";
  18. echo'Longest query length: ' . $longestTime . "";
  19. echo"Longest query: " .$longestQuery . "";

Advanced Profiler Usage高级使用方法

In addition to query inspection, the profiler also allows the developer to filter which queries get profiled. 

The following methods operate on a Zend_Db_Profiler instance:

除了可以对查询的检查分析,分析器也使开发人员能够分析过滤查询。Zend_Db_Profiler提供了相关的操作方法。

Filter by query elapsed time 通过查询时间进行过滤

setFilterElapsedSecs() allows the developer to set a minimum query time before a query is profiled. 

To remove the filter, pass the method a NULL value.

setFilterElapsedSecs()允许开发人员可以设置一个最小的查询时间,来过滤查询。删除过滤器,只需要设置为NULL即可。

  1. // Only profile queries that take at least 5 seconds:
  2. $profiler->setFilterElapsedSecs(5);
  3.  
  4. // Profile all queries regardless of length:
  5. $profiler->setFilterElapsedSecs(null);

Filter by query type 通过查询类型过滤

setFilterQueryType() allows the developer to set which types of queries should be profiled; to profile multiple types, logical OR them. Query types are defined as the followingZend_Db_Profiler constants:

通过使用setFilterQueryType() 方法,开发人员可以根据类型来过滤查询。分析器Zend_Db_Profiler类中定义了多种查询类型常量。如下:

  • Zend_Db_Profiler::CONNECT: connection operations, or selecting a database.链接操作,或者选择数据库

  • Zend_Db_Profiler::QUERY: general database queries that do not match other types. 没有具体匹配类型的查询

  • Zend_Db_Profiler::INSERT: any query that adds new data to the database, generallySQL INSERT.INSERT 插入语句

  • Zend_Db_Profiler::UPDATE: any query that updates existing data, usuallySQL UPDATE. UPDATE更新修改语句

  • Zend_Db_Profiler::DELETE: any query that deletes existing data, usuallySQL DELETE. DELETE删除语句

  • Zend_Db_Profiler::SELECT: any query that retrieves existing data, usuallySQL SELECT. SELECT语句

  • Zend_Db_Profiler::TRANSACTION: any transactional operation, such as start transaction, commit, or rollback. 事务处理语句例如commit和rollback

As with setFilterElapsedSecs(), you can remove any existing filters by passingNULL as the sole argument.

使用setFilterElapsedSecs(),通过设置参数为NULL,你可以删除任何现有的过滤规则。

  1. // profile only SELECT queries
  2. $profiler->setFilterQueryType(Zend_Db_Profiler::SELECT);
  3.  
  4. // profile SELECT, INSERT, and UPDATE queries
  5. $profiler->setFilterQueryType(Zend_Db_Profiler::SELECT |
  6.                               Zend_Db_Profiler::INSERT |
  7.                               Zend_Db_Profiler::UPDATE);
  8.  
  9. // profile DELETE queries
  10. $profiler->setFilterQueryType(Zend_Db_Profiler::DELETE);
  11.  
  12. // Remove all filters
  13. $profiler->setFilterQueryType(null);

Retrieve profiles by query type 设置分析查询的类型

Using setFilterQueryType() can cut down on the profiles generated.  

However, sometimes it can be more useful to keep all profiles, but view only those you need at a given moment. 

Another feature of getQueryProfiles() is that it can do this filtering on-the-fly, by passing a query type (or logical combination of query types) as its first argument; seethis section for a list of the query type constants.


使用 setFilterQueryType() 可以过滤查询。但是,有时需要多种过滤类型同时起作用。 getQueryProfiles()的第一个参数不仅可以是一个查询类型常量,也可以是对查询类型进行逻辑运算组合。如下:

  1. // Retrieve only SELECT query profiles
  2. $profiles = $profiler->getQueryProfiles(Zend_Db_Profiler::SELECT);
  3.  
  4. // Retrieve only SELECT, INSERT, and UPDATE query profiles
  5. $profiles = $profiler->getQueryProfiles(Zend_Db_Profiler::SELECT |
  6.                                         Zend_Db_Profiler::INSERT |
  7.                                         Zend_Db_Profiler::UPDATE);
  8.  
  9. // Retrieve DELETE query profiles
  10. $profiles = $profiler->getQueryProfiles(Zend_Db_Profiler::DELETE);

Specialized Profilers  特定的分析器

A Specialized Profiler is an object that inherits from Zend_Db_Profiler. Specialized Profilers treat profiling information in specific ways.

可以通过继承Zend_Db_Profiler实现一个特定的分析器。特定的分析器可以通过特殊的方式返回分析信息

Profiling with Firebug通过Firebug进行性能分析

Zend_Db_Profiler_Firebug sends profiling infomation to the? Firebug ? Console. All data is sent via the Zend_Wildfire_Channel_HttpHeaders component which usesHTTP headers to ensure the page content is not disturbed. 

Debugging AJAX requests that require cleanJSON and XML responses is possible with this approach.

通过Zend_Db_Profiler_Firebug 将性能分析信息输出到Firebug 的Console控制台。通过Zend_Wildfire_Channel_HttpHeaders的组件设置HTTP头发送所有的数据,以确保页面内容不被干扰。通过这种方法,当用户调试AJAX请求时,可以保证响应JSON和XML不会掺杂多余的信息。

Requirements:要求 

  • Firefox Browser ideally version 3 but version 2 is also supported. 较新的火狐浏览器

  • Firebug Firefox Extension which you can download from ? https://addons.mozilla.org/en-US/firefox/addon/1843. 安装Firebug 

  • FirePHP Firefox Extension which you can download from ? https://addons.mozilla.org/en-US/firefox/addon/6149.安装FirePHP 

Example #1 DB Profiling with Zend_Controller_Front 通过Zend_Controller_Front做DB性能分析

  1. // In your bootstrap file
  2.  
  3. $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
  4. $profiler->setEnabled(true);
  5.  
  6. // Attach the profiler to your db adapter
  7. $db->setProfiler($profiler);
  8.  
  9. // Dispatch your front controller
  10.  
  11. // All DB queries in your model, view and controller
  12. // files will now be profiled and sent to Firebug

Example #2 DB Profiling without Zend_Controller_Front 不采用Zend_Controller_Front做DB性能分析

  1. $profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
  2. $profiler->setEnabled(true);
  3.  
  4. // Attach the profiler to your db adapter
  5. $db->setProfiler($profiler);
  6.  
  7. $request  = new Zend_Controller_Request_Http();
  8. $response = new Zend_Controller_Response_Http();
  9. $channel  = Zend_Wildfire_Channel_HttpHeaders::getInstance();
  10. $channel->setRequest($request);
  11. $channel->setResponse($response);
  12.  
  13. // Start output buffering
  14. ob_start();
  15.  
  16. // Now you can run your DB queries to be profiled
  17.  
  18. // Flush profiling data to browser
  19. $channel->flush();
  20. $response->sendHeaders();

具体的使用方法,在FirePHP 的官方网站已经讲的很详细了。可以参考完成相关配置和使用。


-----------

对译文与原文在含义上的差异而造成的误解不承担任何责任。仅供参考。 



------分隔线----------------------------
------分隔线----------------------------

最新技术推荐