B
B
BadassRolf2017-08-10 12:05:57
Yii
BadassRolf, 2017-08-10 12:05:57

How to cache data in Yii2?

I wrote my own class with the derivation of certain data from the table.
How can they be cached and displayed with a key now in the same class?
I read the documentation, I did not understand anything.
It seems that you need to configure the cache component and set the yii\caching\DbCache class.
In the end, I got completely confused.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Valentine, 2017-08-10
@Tpona

Have you created a table?

CREATE TABLE cache (
    id char(128) NOT NULL PRIMARY KEY,
    expire int(11),
    data BLOB
);

Component for working with cache : Yii::$app->cache
In the place where you get the data (from the database or somewhere else), first check if the data is in the cache:
Yii::$app->cache->exists( "your key");
If there is, get the data from the cache
$data = Yii::$app->cache->get("yourkey");
If not, take the data from where you are currently taking it and immediately save it to the cache:
Yii::$app->cache->get("yourkey", $data);
You also need to take into account that the data can be updated in the original source, and after updating this data, you need to reset the cache.
In general, everything is quite accessible and written in Russian here: https://yiiframework.com.ua/ru/doc/guide/2/caching...

D
Denis Shevchenko, 2017-08-10
@densisss

You can use any kind of cache (File, DB, Memcached, Redis...). The file cache is used by default, for the DB cache you need to create a table in the database.
Example cache in view:

<?php if ($this->beginCache('_header')): ?>
    <header></header>
<?php
    $this->endCache();
endif;
?>

Example in code:
$response = \Yii::$app->cache->getOrSet('categoriesFilterHierarchy', function () { //ищу в кэше переменную с ключом 'categoriesFilterHierarchy', если не нахожу, то обращаюсь в БД и кеширую на 600 секунд 
            $categories = self::find()->orderBy('place ASC')->all();
            return $categories;
        },600);

M
Maxim Timofeev, 2017-08-10
@webinar

I wrote my own class with the derivation of certain data from the table

What's wrong with the standard model? And since you wrote it - give the code to understand what we are talking about
with what key?
Yes, there is a ready-made example in the docs:
www.yiiframework.com/doc-2.0/guide-caching-overvie...
'cache' => [
    'class' => 'yii\caching\DbCache',
    // 'db' => 'mydb',
    // 'cacheTable' => 'my_cache',
]

if you want to store the cache in the database, then yes
www.yiiframework.com/doc-2.0/yii-caching-dbcache.html
Ask specific questions - unravel

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question