hyperia-sk / yii2-clear-cache-behavior

The behavior for Yii2 to clearing cache on specific events
MIT License
0 stars 1 forks source link
behavior cache yii2 yii2-behaviors

Yii2 clear cache behavior

GitHub license Latest Stable Version

The behavior for Yii2 to clearing cache on specific events

Instalation

The preferred way to install this extension is through composer.

Either run

composer require hyperia/yii2-clear-cache-behavior:"*"

or add

"hyperia/yii2-clear-cache-behavior": "*"

to the require section of your composer.json.

Configuration (usage)

In ActiveRecord Model class to invalidate tag after insert, update or delete


use yii\db\ActiveRecord;
use hyperia\behaviors\ClearCacheBehavior;

class Model extends ActiveRecord
{
    private const CACHE_KEY = '~model~';

    public function behaviors()
    {
        return [
            ...
            'clearCache' => [
                'class' => ClearCacheBehavior::class,
                'events' => [
                    ActiveRecord::EVENT_AFTER_INSERT,
                    ActiveRecord::EVENT_AFTER_UPDATE,
                    ActiveRecord::EVENT_AFTER_DELETE
                ],
                'type' => ClearCacheBehavior::TYPE_INVALIDATE_TAG,
                'value' => static::CACHE_KEY
            ],
        ];
    }
}

Parameter description

events

array

Determinantes on which event would be cache deleted. When you want set up Event with same settings.

Default value:

[
    ActiveRecord::EVENT_AFTER_INSERT,
    ActiveRecord::EVENT_AFTER_UPDATE,
    ActiveRecord::EVENT_AFTER_DELETE
]

cache

string

Name of cache component in yii components configuration
Default: "cache"

value

string | array | Closure
Determinantes which part of cache would be deleted ONLY WHEN EVENTS IS SET

type

string
Sets how the cache will be deleted ONLY WHEN EVENTS IS SET
Types:

events_with_settings

array
Array which represents setting of multiple events. Determinantes on which event would be cache deleted. When you want set up multiple Events

Simple example:

    'eventsWithSettings' => [
          \yii\web\Controller::EVENT_BEFORE_ACTION => [
              'type' => ClearCacheBehavior::TYPE_INVALIDATE_TAG,
              'value' => static::CACHE_KEY
          ],
          \yii\web\Controller::EVENT_AFTER_ACTION => [
              'type' => ClearCacheBehavior::TYPE_DELETE,
              'value' => function($event) use ($model) {
                  return $model->id;
              }
          ]
    ],