CacheInvalidateBehavior.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. <?php
  2. namespace common\behaviors;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\caching\TagDependency;
  6. use yii\db\ActiveRecord;
  7. /**
  8. * CacheInvalidateBehavior automatically invalidates cache by specified keys or tags
  9. * public function behaviors()
  10. * {
  11. * return [
  12. * [
  13. * 'class' => CacheInvalidateBehavior::className(),
  14. * 'tags' => [
  15. * 'awesomeTag',
  16. * function($model){
  17. * return "tag-{$model->id}"
  18. * }
  19. * ],
  20. * 'keys' => [
  21. * 'awesomeKey',
  22. * function($model){
  23. * return "key-{$model->id}"
  24. * }
  25. * ]
  26. * ],
  27. * ];
  28. * }
  29. * ```
  30. * @package common\behaviors
  31. */
  32. class CacheInvalidateBehavior extends Behavior
  33. {
  34. /**
  35. * @var string Name of cache componentj
  36. */
  37. public $cacheComponent = 'cache';
  38. /**
  39. * @var array List of tags to invalidate
  40. */
  41. public $tags = [];
  42. /**
  43. * @var array List of keys to invalidate
  44. */
  45. public $keys = [];
  46. /**
  47. * @var
  48. */
  49. private $cache;
  50. /**
  51. * Get events list.
  52. * @return array
  53. */
  54. public function events()
  55. {
  56. return [
  57. ActiveRecord::EVENT_AFTER_DELETE => 'invalidateCache',
  58. ActiveRecord::EVENT_AFTER_INSERT => 'invalidateCache',
  59. ActiveRecord::EVENT_AFTER_UPDATE => 'invalidateCache',
  60. ];
  61. }
  62. /**
  63. * Invalidate cache connected to model.
  64. * @return bool
  65. */
  66. public function invalidateCache()
  67. {
  68. if (!empty($this->keys)) {
  69. $this->invalidateKeys();
  70. }
  71. if (!empty($this->tags)) {
  72. $this->invalidateTags();
  73. }
  74. return true;
  75. }
  76. /**
  77. * Invalidates
  78. */
  79. protected function invalidateKeys()
  80. {
  81. foreach ($this->keys as $key) {
  82. if (is_callable($key)) {
  83. $key = call_user_func($key, $this->owner);
  84. }
  85. $this->getCache()->delete($key);
  86. }
  87. }
  88. /**
  89. *
  90. */
  91. protected function invalidateTags()
  92. {
  93. TagDependency::invalidate(
  94. $this->getCache(),
  95. array_map(function ($tag) {
  96. if (is_callable($tag)) {
  97. $tag = call_user_func($tag, $this->owner);
  98. }
  99. return $tag;
  100. }, $this->tags)
  101. );
  102. }
  103. /**
  104. * @return \yii\caching\Cache
  105. */
  106. protected function getCache()
  107. {
  108. return $this->cache ?: Yii::$app->{$this->cacheComponent};
  109. }
  110. }