1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace yii\db; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Trait CacheableQueryTrait provides methods to cache query execution result. |
7
|
|
|
* |
8
|
|
|
* The class that uses this trait must have the $db property: |
9
|
|
|
* @property Connection $db |
10
|
|
|
* |
11
|
|
|
* @author hubeiwei <[email protected]> |
12
|
|
|
* @author Dmytro Naumenko <[email protected]> |
13
|
|
|
* @since 2.0.14 |
14
|
|
|
*/ |
15
|
|
|
trait CacheableQueryTrait |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var int the default number of seconds that query results can remain valid in cache. |
19
|
|
|
* Use 0 to indicate that the cached data will never expire. And use a negative number to indicate |
20
|
|
|
* query cache should not be used. |
21
|
|
|
* @see cache() |
22
|
|
|
*/ |
23
|
|
|
public $queryCacheDuration; |
24
|
|
|
/** |
25
|
|
|
* @var \yii\caching\Dependency the dependency to be associated with the cached query result for this command |
26
|
|
|
* @see cache() |
27
|
|
|
*/ |
28
|
|
|
public $queryCacheDependency; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Enables query cache for this command or query. |
32
|
|
|
* @param int $duration the number of seconds that query result of this command or query can remain valid in the cache. |
33
|
|
|
* If this is not set, the value of [[Connection::queryCacheDuration]] will be used instead. |
34
|
|
|
* Use 0 to indicate that the cached data will never expire. |
35
|
|
|
* @param \yii\caching\Dependency $dependency the cache dependency associated with the cached result. |
36
|
|
|
* @return $this the command or query object itself |
37
|
|
|
*/ |
38
|
|
|
public function cache($duration = null, $dependency = null) |
39
|
|
|
{ |
40
|
|
|
$this->queryCacheDuration = $duration !== null ? $duration : $this->db->queryCacheDuration; |
41
|
|
|
$this->queryCacheDependency = $dependency; |
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Disables query cache for this command or query. |
47
|
|
|
* @return $this the command or query object itself |
48
|
|
|
*/ |
49
|
|
|
public function noCache() |
50
|
|
|
{ |
51
|
|
|
$this->queryCacheDuration = -1; |
52
|
|
|
return $this; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* Checks, whether caching is enabled |
57
|
|
|
* @return bool |
58
|
|
|
*/ |
59
|
|
|
public function hasCache() |
60
|
|
|
{ |
61
|
|
|
return $this->queryCacheDuration !== null || $this->queryCacheDependency !== null; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|