Answer the question
In order to leave comments, you need to log in
Yii2 How to Cache Widgets Correctly?
Is it possible to cache a widget like PageCache?
Basically, it is advised to cache fidgets as fragments, but this cache is already applied in the view and the widget call logic is still processed every time.
You can also cache the place where the widget is called, but again, the widget can already be in dozens of places and you don’t want to rewrite a bunch of code for the sake of one widget, so the Widget can work outside the Yii application
Only a crutch option comes to mind Place the widget inside another, and already there cache it as a fragment
Answer the question
In order to leave comments, you need to log in
It is possible like this:
class MyWidget extends yii\base\Widget
{
public static function widget($config = [])
{
$data = Yii::$app->cache->get('key'); // логику формирования ключа нужно сделать исходя из задачи
if ($data === false) {
$data = parent::widget($config);
Yii::$app->cache->set('key', $data);
}
return $data;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question