black-room-boy
black-room-boy

Reputation: 659

How to use query caching in yii2 ActiveRecord

I am quoting the guide:

``Query caching is a special caching feature built on top of data caching. It is provided to cache the result of database queries.

Query caching requires a DB connection and a valid cache application component. The basic usage of query caching is as follows, assuming $db is a yii\db\Connection instance:

$result = $db->cache(function ($db) {

    // the result of the SQL query will be served from the cache
    // if query caching is enabled and the query result is found in the cache
    return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();

});

``

I do not think that I will manually create db connection in AR classes. So how to do this in my AR models ?

I have asked the same question on yii2 forum but I got no answer. It seems that people do not know how to do query caching in Active Record.

Upvotes: 3

Views: 11204

Answers (2)

JimHansen
JimHansen

Reputation: 74

Yii 2 now requires closures to wrap the query. AR does a query eventually so you can put that in the closure. In an AR class, get the db and wrap the query you want to use. The closure has a signature function($db) and you usually need to access more variables, so add use($variable) to make variables visible within the closure.

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

If you write to the db, the cache above won't know about it until the cache duration expires. So dependency should be added to the cache function to tell it when to invalidate the cache. Dependency gets complicated fast... http://www.yiiframework.com/doc-2.0/yii-caching-dependency.html

Upvotes: 3

TomaszKane
TomaszKane

Reputation: 815

maybe this help: yii2 issues on github

qiangxue commented on 11 Jan 2014

In 2.0, you need to use the following code:

$db->beginCache();
// your db query code here...
$db->endCache();

Upvotes: 0

Related Questions