You maybe using cached data on your web server (I hope it is NGINX) to store your Role Based Access Control (RBAC), Sitemap or Application Config and Settings. Hopefully when any of these modules are updated you include code to trigger the flushing of the appropriate cache store.
But sometimes you just want a lazy method to make sure that all your application cache is fresh. So why not add the following action to your SiteController.
Site Controller
Add actionFlushCache
to your SiteController
/**
* Flush Cache
* @return \yii\web\Response
*/
public function actionFlushCache()
{
Yii::$app->cache->flush();
Yii::$app->session->setFlash('success', 'Cache successfully flushed');
return $this->goHome();
}
Then to prevent anyone from accessing this new action, add flush-cache
to the yii\filters\AccessControl
behaviour (line 15
).
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::class,
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'flush-cache', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::class,
'actions' => [
'logout' => ['post'],
],
],
];
}
Now any logged on user can flush all the application cache stores by using the following url https://my-yii2-app-url/site/flush-cache
Version 2
We could change our flush-cache
method so that a specific cache store could be deleted. The following web controller action has a parameter called $key
. If this is specified then an attempt is made to flush the specific cache. If it isn't specified then all cache stores will be flushed.
/**
* Flush Cache
* @return \yii\web\Response
* @param string $key
*/
public function actionFlushCache($key = null)
{
if ($key)
Yii::$app->cache->delete($key);
else
Yii::$app->cache->flush();
Yii::$app->session->setFlash('success', ($key ? '"' . $key . '" ' : '') .
'Cache successfully flushed');
return $this->goHome();
}
Now if we want to only delete our cache store called sitemap
, we can run the following url https://my-yii2-app-url/site/flush-cache?key=sitemap