Invalid Doctrine 2 Result Cache

I use the Doctrine 2 result cache in the query, getting the number of new user messages (messaging application):

$query->useResultCache(true, 500, 'messaging.nb_new_messages.'.$userId); 

I tried to make this cache invalid (in my object repository):

 public function clearNbNewMessagesOfUserCache($userId) { $cacheDriver = $this->getEntityManager()->getConfiguration()->getResultCacheImpl(); $result = $cacheDriver->delete('skepin_messaging.nbNewMessages.'.$userId); if (!$result) { return false; } return $cacheDriver->flushAll(); } 

So I do not need to make a useless request on every page of my site.

My questions are: - is this a recommended practice? Will I end up having problems?

+6
caching apc doctrine2 cache-invalidation
source share
1 answer


I had an idea to build an onFlush hook. There you have all the entities queued for insertions, updates, and deletions, so you can invalidate caching depending on the name and identifier of an object, etc.

Unfortunately, I have not created event listeners yet, but I definitely plan to build such a thing for my project.

Here is a link to the doctrine documentation for the onFlush event

Edit: There is an even simpler way to implement events. In an entity class, you can add @HasLifecycleCallbacks in the annotations, and then you can define the function using the @PreUpdate or @PrePersist annotation. Each time this model is updated or saved, this function will be called.

 /** * @Entity * @Table(name="SomeEntity") * @HasLifecycleCallbacks */ class SomeEntity { ... /** * @PreUpdate * @PrePersist */ public function preUpdate() { // This function is called every time this model gets updated // or a new instance of this model gets persisted // Somethink like this maybe... // I have not yet completely thought through all this. $cache->save(get_class($this) . '#' . $this->getId(), $this); } } 

Maybe this can be used to invalidate every single instance of an object?

+2
source share

Source: https://habr.com/ru/post/918832/


All Articles