Thanks for your response.
I already resolved it with the same approach; the only problem was Cache without dependency doesn’t invalidate itself if we call the same query with dependency injection.
Step 1: Call Query Without Dependency
First, get the response from Cache () without dependency:
$model = UserDetails::find()->cache('3600')->where(['user_id' => 1])->one();
// To make it easy for understanding Let's assume CACHE_ID = ABCD
/* CACHE_ID with ABCD return below response */
[
'id' => 1,
'name' => 'John Doe',
'number' => '1800111222'
]
Step 2: Add dependency
Now add the dependency in the query and invalidate
it in the afterSave
function:
$dependency = new TagDependency(['tags' => 'user_cache']);
$model = UserDetails::find()->cache('3600', $dependency)->where(['user_id' => 1])->one();
// Let's assume for this dependency cache the CACHE_ID = PQRS
// In Model file
// Invalidate cache once user perform update
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
TagDependency::invalidate(Yii::$app->cache, 'user_cache');
}
Step 3: Update Data
Now made update in the name: Changed to “Harry Porter”,
As we have added invalidate tag in the AFTER SAVE method, it will invalidate the “ID = PQRS” Cache. It is working perfectly fine.
$dependency = new TagDependency(['tags' => 'user_cache']);
$model = UserDetails::find()->cache('3600', $dependency)->where(['user_id' => 1])->one();
//Cache with the value PQRS is invalidated.
// But the query still returns the value from the ABCD cache.
[
'id' => 1,
'name' => 'John Doe', // It should be Harry Porter
'number' => '1800111222'
]
The Problem
The last query should load the data from the cache “PQRS” with dependency injection. However, the data was still loading from the “ABCD” CACHE, which has no dependency injection STEP 1.
Time solved the issue:
After 1 hour, when the ABCD cache automatically expires, the above code will work perfectly and return the PQRS value.
Hope you got the point.