consik / yii2-cachecleaner
Yii2 behavior for deleting cache values on component event
Installs: 9
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- yiisoft/yii2: *
This package is not auto-updated.
Last update: 2024-12-21 21:47:23 UTC
README
Installation
The preferred way to install this extension is through composer.
Either run
composer require consik/yii2-cachecleaner
or add
"consik/yii2-cachecleaner": "^1.0"
CacheCleanerBehavior class description
Deletes cache after defined events.
Properties
array $events = []
- Associative array where key is event name, value(array|string|null) is a cache key(s) to deletestring $cacheComponent = 'cache'
- Name of the application cache component
Public methods
boolean deleteCache(string|array $key)
- Deletes cache value(s)boolean flushCache()
- Deletes all cache values
ARUpdateCCBehavior class description. #docs
Deletes cache values after updating ActiveRecord attributes
Properties
array $attributes = []
- Associative array, where array keys is attributes name, array value is cache value(s) keysstring $cacheComponent = 'cache'
- Name of the application cache component
See DocBlock for usage examples.
Examples
Autodelete cache after AR update
Simple use case: We have cached AR object somewhere in our app:
<?php ... if (!$model = Yii::$app->cache->get('cachedModel')) { $model = ARModel::findOne($modelID); Yii::$app->cache->set('cachedModel', $model); } ...
So, if somewhere in applicaton we change or delete this AR data, we have to delete our cache value.
Just use CacheCleanerBehavior in your ARModel:
<?php public function behaviors() { return [[ 'class' => CacheCleanerBehavior::className(), //'cacheComponent' => 'cache', //you can define your app cache component 'events' => [ ActiveRecord::EVENT_AFTER_UPDATE => 'cachedModel' ActiveRecord::EVENT_BEFORE_DELETE => 'cachedModel' ] ]]; }
NOTE! When component initialize behaviors there is no attributes! To set cache keys with object attributes use callable param for defining. #DocBlock
Using CacheUpdateEvent
There is a special class in package for triggering events when you change cache values, where you can send to handler action changed cache key(s).
You can use this class with CacheCleanerBehavior if you want delete different keys using one event name.
Example:
<?php public function behaviors() { return [[ 'class' => CacheCleanerBehavior::className(), 'events' => [ YOUR_EVENT_NAME => null ] ]]; } ... function someComponentAction() { ... $this->trigger(YOUR_EVENT_NAME, new CacheUpdateEvent([ 'keys' => ['keyName1', 'keyName2'], ])); ... }
Other options for defining $events property
See the doc block for CacheCleanerBehavior::$events