Maslosoft Framework Logo Maslosoft Framework Documentation
Flexible Application Foundation


Cache Dependent Clear

Some components might store some data in cache. When they are updated, cache need to be cleared, so that new data will be pulled from database.

There is a event handler helper for this purpose, the CacheDependentClear class. It will simplify attaching events for model-related cached entities.

It need to be attached to Mangan configuration. It need to be added as an array element to $eventHandlers.

It need to have these properties configured at minimum:

Class to which attach cache dependency clear, after model CRUD operations.

This is equivalent of calling:

Event::on($attachTo, ...)

Callback for creating cache keys.

It takes model as a first parameter and Event as a second one.

Example:

function($model)
{
        return get_class($model) . '#' . $model->id;
}

It can also return array of keys, if many cache entities should be removed:

function($model)
{
        return [1, 2, 3];
}

Additionally $instanceId can be defined to point at which cache element event handler should operate.

Example of adding CacheDependentClear to Mangan:

// Mangan additional configuration
return [
    'eventHandlers' => [
        // Clear page links cache on menu updating
        [
            'class' => CacheDependentClear::class,
            'attachTo' => PageMenu::class,
            'createKey' => function(PageMenu $menu)
            {
                return [
                    PageLinks::getNameKey($menu->code),
                    PageLinks::getPagesKey($menu->code)
                ];
            }
        ]
    ]
];

Above example will clear cache of PageLinks class, after PageMenu will be updated, changed or trashed.