asm89 / twig-cache-extension

The missing cache extension for Twig. Caching template fragments with Twig.
MIT License
388 stars 27 forks source link

How to invalidate cache when data change? #50

Open MacDada opened 5 years ago

MacDada commented 5 years ago

Hi,

we want to cache templates that use lazily fetched data. Something like this:

class ViewModel
{
    public function getItem(): Item
    {
        $this->repository->findItem();
    }
}
{% cache 'v1/show_item' viewModel %}
        {{ viewModel.item.title }}
{$ endcache %}

Of course, most of the time our logic is more complicated than that. There is more template stuff to cache and more data stuff to cache. By using VM inside cached part of template, we have a lazily loaded entity (or entities, or other data), which seems cool enough to use this extension.

The problem is: how do we invalidate the cache when values in Item change?

We could use GenerationalCacheStrategy, but that would mean we cannot have Item (and other stuff) lazily–loaded.

So we want to invalidate cache „manually” (but still in code ;)) when necessary. For example, there is code that changes title in some Item – then we'd like to call something like this: invalidateCache('show_item_'.$item->getId()).

But what if there are more parameters to take care of? Like current user status, etc?

Should we try cache tags? What's the best way to implement them here?

Any other ideas?

As always,

There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton

rvanlaak commented 5 years ago

Can advise you to include a timestamp from the model (like dateModified) in the cache key together with the model id. That timestamp should be the one that changes once the data changes.

MacDada commented 5 years ago

Can advise you to include a timestamp from the model (like dateModified) in the cache key together with the model id. That timestamp should be the one that changes once the data changes.

@rvanlaak How do I know the timestamp when i include the template with ViewModel? VM would have to call the DB to load entity (or entities or other data). And that would make it not "lazy-loaded". And probably make caching not worth it (at least at the level of the template).

rvanlaak commented 5 years ago

You would have to include a timestamp with the view model?

As this isn't an issue with this extension, I would also advise you to use StackOverflow instead of creating an issue, as it will be way easier to reach more devs over there that can help you to formulate an answer on your question.