Here’s a very simply dependency which helps you to remove specific items from the cache. It does not require another query to find out if your record has changed. Instead it just uses another cache key to inform the dependency about the change.
I’ve kept it very simple, so you use it like this:
// At the query:
$dependency = new FlushableDependency($id,'Post');
$post = Post::model()->cache(3600,$dependency)->findByPk($id);
// In the model:
Maybe i’ll add a behavior to the extension which you can attach to your ActiveRecords to automate this. But i’m hesitating because it may not catch all updates (e.g. calls to saveAttributes()).
I think this is a really great idea, especially in combination with afterSave() etc. and will take a lot of load off the db.
Regarding your idea of making this a behavior: You think newcomers would easily get “tricked” by thinking saveAttributes() calls afterSave() which it doesn’t? I agree that this is somewhat weird but wouldn’t they have the same problem implementing this dependency by themselves?
Exactly. We should have events for this. I hope we get them in Yii 2.0.
Not sure what you mean. But if we don’t automate too much, there’s a better chance that the developer understands what this dependency does. So he will know, that whenever he updates (either by save() or saveAttributes()) or deletes a record, he also has to flush the respective ids from the cache through this dependency.
Bethrenzen raised the valid argument, that this dependency could also be used for page/fragment caching. In this case the $model does not make sense. So i changed the interface slightly and realeased version 1.1.0.
I hope such an interface change is still acceptable on the first day
You can not have more than one COutputCache for the same page. So either configure your filter to be active for specific pages only or take another approach. Apart from that i can’t see, where you use the flushable behavior at all.
Much better . But you should include the provider id in the calls to flushItem($this->id,‘Provider’) and FlushableDependency($id, ‘Provider’). Otherwhise whenever you update one provider you flush all from the cache. You’ll probably use something like $id = isset($_GET[‘id’]) ? (int) $_GET[‘id’] : -1; or something to get the $id in the controller.