S
S
shasoft2019-06-10 17:41:07
caching
shasoft, 2019-06-10 17:41:07

Is there a package for Laravel/Lumen that caches before the event (instead of time)?

We are looking for a package for caching data that caches not for a certain time, but until certain events occur. Those. for example, I cached the user's data before the events of changing some of its parameters, or changing roles. When an event occurs, I send it to the CACHE and it removes all cache items to which this event is attached.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Ukolov, 2019-06-10
@shasoft

Most likely, there is no such package, because the reset logic will be closely related to the event that is unique to the project, and there will be almost nothing besides this logic.
For me it looks like this:

<?php
declare(strict_types=1);

namespace App\Listeners;

use Illuminate\Cache\CacheManager;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\Str;

class CachePurger
{
    private $events = [
        SomeEvent::class,
        OtherEvent::class => 'customHandlerName',
    ];

    /**
     * @var CacheManager
     */
    private $cacheManager;

    public function __construct(CacheManager $cacheManager)
    {
        $this->cacheManager = $cacheManager;
    }

    public function subscribe(Dispatcher $events): void
    {
        foreach ($this->events as $event => $handler) {
            if (is_numeric($event)) {
                $event = $handler;
                $handler = Str::camel('when_' . class_basename($event));
            }

            if (method_exists($this, $handler)) {
                $events->listen($event, [$this, $handler]);
            }
        }
    }

    private function whenSomeEvent(SomeEvent $event): void
    {
        $this->cacheManager->forget(...);
    }

    private function customHandlerName(OtherEvent $event): void
    {
        $this->cacheManager->forget(...);
    }
}

class EventServiceProvider extends ServiceProvider
{
    protected $subscribe = [
        CachePurger::class,
    ];
}

https://laravel.com/docs/5.8/events#event-subscribers

A
Alexander Aksentiev, 2019-06-10
@Sanasol

Why is there a package for this?
Make a Listener/Event and delete the required cache in the Listener handler

R
Rustam Sadykov, 2019-06-10
@TrueKanonir

What if you use an observer? User data is cached, when editing data, reset the cache in the observer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question