Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
771 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 Reply

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...