GroupDependency.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\base\InvalidConfigException;
  9. /**
  10. * GroupDependency marks a cached data item with a group name.
  11. *
  12. * You may invalidate the cached data items with the same group name all at once
  13. * by calling [[invalidate()]].
  14. *
  15. * @author Qiang Xue <[email protected]>
  16. * @since 2.0
  17. */
  18. class GroupDependency extends Dependency
  19. {
  20. /**
  21. * @var string the group name. This property must be set.
  22. */
  23. public $group;
  24. /**
  25. * Generates the data needed to determine if dependency has been changed.
  26. * This method does nothing in this class.
  27. * @param Cache $cache the cache component that is currently evaluating this dependency
  28. * @return mixed the data needed to determine if dependency has been changed.
  29. * @throws InvalidConfigException if [[group]] is not set.
  30. */
  31. protected function generateDependencyData($cache)
  32. {
  33. if ($this->group === null) {
  34. throw new InvalidConfigException('GroupDependency::group must be set');
  35. }
  36. $version = $cache->get([__CLASS__, $this->group]);
  37. if ($version === false) {
  38. $version = $this->invalidate($cache, $this->group);
  39. }
  40. return $version;
  41. }
  42. /**
  43. * Performs the actual dependency checking.
  44. * @param Cache $cache the cache component that is currently evaluating this dependency
  45. * @return boolean whether the dependency is changed or not.
  46. * @throws InvalidConfigException if [[group]] is not set.
  47. */
  48. public function getHasChanged($cache)
  49. {
  50. if ($this->group === null) {
  51. throw new InvalidConfigException('GroupDependency::group must be set');
  52. }
  53. $version = $cache->get([__CLASS__, $this->group]);
  54. return $version === false || $version !== $this->data;
  55. }
  56. /**
  57. * Invalidates all of the cached data items that have the same [[group]].
  58. * @param Cache $cache the cache component that caches the data items
  59. * @param string $group the group name
  60. * @return string the current version number
  61. */
  62. public static function invalidate($cache, $group)
  63. {
  64. $version = microtime();
  65. $cache->set([__CLASS__, $group], $version);
  66. return $version;
  67. }
  68. }