Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

caching - Yii2 ActiveRecord cache

How to use ActiveRecotd cache for Yii 2? I did't find any examples in official docs. In Google I found 2 examples, first is:

$db = self::getDb();
$object = $db->cache(function ($db) use($id) {
    return self::findOne($id);
});

But it doesn't work for Model, I tested with updated framework. Other example is:

$data = Yii::$app->cache->get('some_var_' . $id);
if ($data === false)
{
    $data = self::findOne($id);
    Yii::$app->cache->set('some_var_' . $id, $data, 60);
}

It's working fine, but it's not ActiveRecord caching it's data caching, So we haven't got ActiveRecord caching in Yii 2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

1) Use cache like that:

$db = Yii::$app->db;// or Category::getDb()
$result = $db->cache(function ($db) use ($id) {
    return Category::find()->where(['id' => $id])->all();
}, CACHE_TIMEOUT);

2) If you may use query dependency, use like that:

$db = Yii::$app->db;// or Category::getDb()
$dep = new DbDependency();
$dep->sql = 'SELECT count(*) FROM category';
$result = $db->cache(function ($db) use ($id) {
    return Category::find()->where(['id' => $id])->all();
}, CACHE_TIMEOUT, $dep);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...