CakePHP Cache::write() Can keys be grouped by mode

2019-04-13 13:53发布

Consider the following;

Cache::write('Model.key1' , 'stuff');
Cache::write('AnotherModel.key1' , 'stuff');
Cache::write('Model.key2' , 'stuff');

Can I delete a group of keys from the Cache?

For instance, if I wanted to clear all cached data for "Model" but leave "AnotherModel" in the cache, I would like to use the following;

Cache::delete('Model.*');

Can this kind of thing be achieved in CakePHP 1.3.x?

Thanks!

2条回答
萌系小妹纸
2楼-- · 2019-04-13 14:07

You can set up a different cache config for each model such that each config has a different path.
http://book.cakephp.org/view/1515/Cache-config

I don't see a way to completely delete all data using the cache class but you could write your own function to delete all of the data (cached files) out of the specific cache directory for the specific model. By using different config files for different models, you can isolate the model's cached data into a unique directory for each model and then manually delete the contents when you want to flush the data for that model.

查看更多
祖国的老花朵
3楼-- · 2019-04-13 14:16

For those just Googling this issue (as I was), Cake 2.2 now supports this kind of functionality (without having to create separate cache configs for each 'group').

There is a little explanation here, although it lacks some details:
http://book.cakephp.org/2.0/en/core-libraries/caching.html#using-groups

But this is what I did in my app and it appears to work well. ;-)

In /app/Config/core.php

Cache::config('default', array(
    'engine' => $engine,
    ...
    'groups' => ['navigation'],
));

Model afterSave hook:

function afterSave($created) {
    // This deletes all keys beginning with 'navigation'
    Cache::clearGroup('navigation');
    parent::afterSave($created);
}

Then in my controller/model that requires an expensive query...

// We create a unique key based on parameters passed in
$cacheKey = "navigation.$sitemapId.$levelsDeep.$rootPageId";
$nav = Cache::read($cacheKey);
if (!$nav) {
    $nav = $this->recursiveFind(
        'ChildPage',
        ['page_id' => $rootPageId],
        $levelsDeep
    );
    Cache::write($cacheKey, $nav);
}
查看更多
登录 后发表回答