1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace JamesMoss\Flywheel; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* CachedQuery |
7
|
|
|
* |
8
|
|
|
* A extension of Query that is able to store results in shared memory (via |
9
|
|
|
* the apc_* functions) so that they can be retieved for future use with |
10
|
|
|
* minimal performance impact. |
11
|
|
|
*/ |
12
|
|
|
class CachedQuery extends Query |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Checks the cache to see if this query exists and returns it. If it's |
16
|
|
|
* not in the cache then the query is run, stored and then returned. |
17
|
|
|
* |
18
|
|
|
* @return Result The result of the query. |
19
|
|
|
*/ |
20
|
|
|
public function execute() |
21
|
|
|
{ |
22
|
|
|
static $apcPrefix = null; |
23
|
|
|
if($apcPrefix === null) { |
24
|
|
|
$apcPrefix = function_exists('apcu_fetch') ? 'apcu' : 'apc'; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
// Generate a cache key by comparing our parameters to see if we've |
28
|
|
|
// made this query before |
29
|
|
|
$key = $this->getParameterHash() . $this->getFileHash(); |
30
|
|
|
|
31
|
|
|
// Try and fetch a cached result object from APC |
32
|
|
|
$funcName = $apcPrefix . '_fetch'; |
33
|
|
|
$success = false; |
34
|
|
|
$result = $funcName($key, $success); |
35
|
|
|
|
36
|
|
|
// If the result isn't in the cache then we run the real query |
37
|
|
|
if (!$success) { |
38
|
|
|
$result = parent::execute(); |
39
|
|
|
$funcName = $apcPrefix . '_store'; |
40
|
|
|
$funcName($key, $result); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $result; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Gets a hash based on the files in the repo directory. If the contents |
48
|
|
|
* of a file changes, or other files are added/deleted the hash will change. |
49
|
|
|
* Uses filematime() for speed when checking for file changes (rather than |
50
|
|
|
* using crc32 or md5 etc) |
51
|
|
|
* |
52
|
|
|
* @return string A 128bit hash in hexadecimal format. |
53
|
|
|
*/ |
54
|
|
|
protected function getFileHash() |
55
|
|
|
{ |
56
|
|
|
$files = $this->repo->getAllFiles(); |
57
|
|
|
$hash = ''; |
58
|
|
|
|
59
|
|
|
foreach ($files as $file) { |
60
|
|
|
$hash.= $file . '|'; |
61
|
|
|
$hash.= (string) filemtime($file) . '|'; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$hash = md5($hash); |
65
|
|
|
|
66
|
|
|
return $hash; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Generates a hash based on the parameters set in the query. |
71
|
|
|
* |
72
|
|
|
* @return string A 128bit hash in hexadecimal format. |
73
|
|
|
*/ |
74
|
|
|
protected function getParameterHash() |
75
|
|
|
{ |
76
|
|
|
$parts = array( |
77
|
|
|
$this->repo->getName(), |
78
|
|
|
serialize((array) $this->limit), |
79
|
|
|
serialize((array) $this->orderBy), |
80
|
|
|
serialize((array) $this->predicate), |
81
|
|
|
); |
82
|
|
|
|
83
|
|
|
return md5(implode('|', $parts)); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|