1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @link https://www.yiiframework.com/ |
4
|
|
|
* @copyright Copyright (c) 2008 Yii Software LLC |
5
|
|
|
* @license https://www.yiiframework.com/license/ |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace yii\caching; |
9
|
|
|
|
10
|
|
|
use Yii; |
11
|
|
|
use yii\base\InvalidConfigException; |
12
|
|
|
use yii\db\Connection; |
13
|
|
|
use yii\di\Instance; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* DbDependency represents a dependency based on the query result of a SQL statement. |
17
|
|
|
* |
18
|
|
|
* If the query result changes, the dependency is considered as changed. |
19
|
|
|
* The query is specified via the [[sql]] property. |
20
|
|
|
* |
21
|
|
|
* For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview). |
22
|
|
|
* |
23
|
|
|
* @author Qiang Xue <[email protected]> |
24
|
|
|
* @since 2.0 |
25
|
|
|
*/ |
26
|
|
|
class DbDependency extends Dependency |
27
|
|
|
{ |
28
|
|
|
/** |
29
|
|
|
* @var string the application component ID of the DB connection. |
30
|
|
|
*/ |
31
|
|
|
public $db = 'db'; |
32
|
|
|
/** |
33
|
|
|
* @var string the SQL query whose result is used to determine if the dependency has been changed. |
34
|
|
|
* Only the first row of the query result will be used. |
35
|
|
|
*/ |
36
|
|
|
public $sql; |
37
|
|
|
/** |
38
|
|
|
* @var array the parameters (name => value) to be bound to the SQL statement specified by [[sql]]. |
39
|
|
|
*/ |
40
|
|
|
public $params = []; |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Generates the data needed to determine if dependency has been changed. |
45
|
|
|
* This method returns the value of the global state. |
46
|
|
|
* @param CacheInterface $cache the cache component that is currently evaluating this dependency |
47
|
|
|
* @return mixed the data needed to determine if dependency has been changed. |
48
|
|
|
* @throws InvalidConfigException if [[db]] is not a valid application component ID |
49
|
|
|
*/ |
50
|
3 |
|
protected function generateDependencyData($cache) |
51
|
|
|
{ |
52
|
|
|
/* @var $db Connection */ |
53
|
3 |
|
$db = Instance::ensure($this->db, Connection::class); |
54
|
3 |
|
if ($this->sql === null) { |
55
|
1 |
|
throw new InvalidConfigException('DbDependency::sql must be set.'); |
56
|
|
|
} |
57
|
|
|
|
58
|
2 |
|
if ($db->enableQueryCache) { |
59
|
|
|
// temporarily disable and re-enable query caching |
60
|
1 |
|
$db->enableQueryCache = false; |
61
|
1 |
|
$result = $db->createCommand($this->sql, $this->params)->queryOne(); |
62
|
1 |
|
$db->enableQueryCache = true; |
63
|
|
|
} else { |
64
|
1 |
|
$result = $db->createCommand($this->sql, $this->params)->queryOne(); |
65
|
|
|
} |
66
|
|
|
|
67
|
2 |
|
return $result; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|