1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @source http://www.coderholic.com/php-database-query-logging-with-pdo/ |
4
|
|
|
* Modified for use with Ajde_Document_Processor_Html_Debugger |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Extends PDO and logs all queries that are executed and how long |
9
|
|
|
* they take, including queries issued via prepared statements. |
10
|
|
|
*/ |
11
|
|
|
class Ajde_Db_PDO extends PDO |
12
|
|
|
{ |
13
|
|
|
public static $log = []; |
14
|
|
|
|
15
|
|
|
public function __construct($dsn, $username = null, $password = null, $options = []) |
16
|
|
|
{ |
17
|
|
|
$options = $options + [ |
18
|
|
|
PDO::ATTR_STATEMENT_CLASS => ['Ajde_Db_PDOStatement', [$this]], |
19
|
|
|
]; |
20
|
|
|
parent::__construct($dsn, $username, $password, $options); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function query($query) |
24
|
|
|
{ |
25
|
|
|
//$cache = Ajde_Db_Cache::getInstance(); |
26
|
|
|
$log = ['query' => $query]; |
27
|
|
|
$start = microtime(true); |
28
|
|
|
//if (!$cache->has($query)) { |
29
|
|
|
|
30
|
|
|
try { |
31
|
|
|
$result = parent::query($query); |
32
|
|
|
} catch (Exception $e) { |
33
|
|
View Code Duplication |
if (config('app.debug') === true) { |
|
|
|
|
34
|
|
|
if (isset($this->queryString)) { |
35
|
|
|
dump($this->queryString); |
|
|
|
|
36
|
|
|
} |
37
|
|
|
dump('Go to '.config('app.rootUrl').'?install=1 to install DB'); |
38
|
|
|
throw new Ajde_Db_Exception($e->getMessage()); |
39
|
|
|
} else { |
40
|
|
|
Ajde_Exception_Log::logException($e); |
|
|
|
|
41
|
|
|
die('DB connection problem. <a href="?install=1">Install database?</a>'); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
//$cache->set($query, serialize($result)); |
46
|
|
|
// $log['cache'] = false; |
47
|
|
|
//} else { |
48
|
|
|
// $result = $cache->get($query); |
49
|
|
|
// $log['cache'] = true; |
50
|
|
|
//} |
51
|
|
|
$time = microtime(true) - $start; |
52
|
|
|
$log['time'] = round($time * 1000, 0); |
53
|
|
|
self::$log[] = $log; |
54
|
|
|
|
55
|
|
|
return $result; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public static function getLog() |
59
|
|
|
{ |
60
|
|
|
return self::$log; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.