CachedBehavior.php 630 B

1234567891011121314151617181920212223242526272829303132
  1. <?php
  2. namespace app\components\behaviors;
  3. use Yii;
  4. use yii\base\Behavior;
  5. use yii\db\ActiveRecord;
  6. class CachedBehavior extends Behavior
  7. {
  8. public $cache_key;
  9. public function events()
  10. {
  11. return [
  12. ActiveRecord::EVENT_AFTER_INSERT => 'deleteCache',
  13. ActiveRecord::EVENT_AFTER_UPDATE => 'deleteCache',
  14. ActiveRecord::EVENT_AFTER_DELETE => 'deleteCache',
  15. ];
  16. }
  17. public function deleteCache()
  18. {
  19. foreach ($this->cache_key as $id){
  20. if( isset($this->owner->id) ){
  21. $key = str_replace( '##', $this->owner->id, $id );
  22. }else{
  23. $key = str_replace( '##', '', $id );
  24. }
  25. Yii::$app->cache->delete($key);
  26. }
  27. }
  28. }