Yii2 CacheCleaner Extension
, (*1)
Installation
The preferred way to install this extension is through composer., (*2)
Either run, (*3)
composer require consik/yii2-cachecleaner
or add, (*4)
"consik/yii2-cachecleaner": "^1.0"
CacheCleanerBehavior class description
Deletes cache after defined events., (*5)
Properties
-
array $events = []
- Associative array where key is event name, value(array|string|null) is a cache key(s) to delete
-
string $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, (*6)
Properties
-
array $attributes = []
- Associative array, where array keys is attributes name, array value is cache value(s) keys
-
string $cacheComponent = 'cache'
- Name of the application cache component
See DocBlock for usage examples., (*7)
Examples
Autodelete cache after AR update
Simple use case:
We have cached AR object somewhere in our app:, (*8)
<?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., (*9)
Just use CacheCleanerBehavior in your ARModel:, (*10)
<?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, (*11)
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)., (*12)
You can use this class with CacheCleanerBehavior if you want delete different keys using one event name., (*13)
Example:, (*14)
<?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, (*15)