mikk150/yii2-tagdependency-invalidator

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

1.2.0 2021-09-15 12:41 UTC

This package is auto-updated.

Last update: 2024-11-15 19:16:35 UTC


README

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