Thursday, March 16, 2017

Flushing the same cached tag in multiple methods

I'm storing a specific query using Cache tags method:

Cache::tags('my_tag')->forever('Foo', 'Bar');

Now, I need to flush the cached tag every time one of N-number of methods are triggered - the methods are mostly CRUD, with some exceptions, and the methods belong to different controllers/models.

The implementation I'm using now is based on an Event and a Listener: every time one of the mentioned CRUD methods is called, I fire an event:

Event::fire(new ClearCache(null, 'my_tag'));

Then the event listener will flush the cache:

Cache::tag($event->tag)->flush();

This is a working solution. However, I need to repeat the Event call (above) in each of the N methods.

I'm wondering: Is there a better way to approach the problem? Any way to "centralize" the cache clearing? For example a class "listening" to whether any of my CRUD methods was called, and then firing the same Event - this would be perfect.



via lesssugar

Advertisement