Yii2 CacheCleaner Extension
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
#docs
ARUpdateCCBehavior class description.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
CacheUpdateEvent
UsingThere 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