mikk150/yii2-tagdependency-invalidator

Invalidates Yii2's TagDependency tags on model update/delete and insert


Keywords
cache, extension, yii2, tagdependency
License
GPL-2.0

Documentation

Yii2 tagdependency invalidation behavior

Build Status codecov

Usage

To use this behavior, add it to model's or components behaviors model

class Book extends yii\base\ActiveRecord
{
    const CACHE_KEY = 'BOOKS_ARE_AWESOME!';

    public function behaviors()
    {
        return [
            [
                'class' => 'mikk150\tagdependency\InvalidateBehavior',
                'tags' => [
                    [
                        self::CACHE_KEY,
                        'id' => 'primaryKey',
                    ],
                ]
            ]
        ]
    }
}

then where you want to use cached models, just do this

public function actionView($id)
{
    return Yii::$app->cache->getOrSet(['book', $id], function () use ($id) {
        return Book::find()->byId($id)->one();
    }, null, new TagDependency([
        'tags' => [
            [
                Book::CACHE_KEY,
                'id' => $id,
            ]
        ]
    ]))
}

if BaseActiveRecord::EVENT_AFTER_UPDATE, BaseActiveRecord::EVENT_AFTER_INSERT or BaseActiveRecord::EVENT_AFTER_DELETE is triggered, then cache is automatically invalidated for this model based on key rules

additionally, you can also clear cache by executing invalidate() on model1