DbDependency.php 2.0 KB

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