DbDependency.php 2.2 KB

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