enchance
enchance

Reputation: 30411

Laravel 5.2: Event when a cache expires

Is there an event we can use when a cache is about to be expire? My plan is to write the data to db before it expires. There are currently 4 events but I don't think neither of them does this.

Also, when are the cache events missed and hit called?

Upvotes: 1

Views: 1719

Answers (1)

ceejayoz
ceejayoz

Reputation: 179994

No, there's no event for expiration. In most cases, Laravel has no involvement in expiration beyond setting an expiration time when the data is stored. The underlying system (Redis, memcached, APC, etc.) handles the actual expiration independently.

vendor/laravel/framework/src/Illuminate/Cache/Respository.php has the various situations missed and hit events occur for (search it for fireCacheEvent calls). Any call that requests data from the cache (Cache::get, Cache::remember, etc.) and doesn't find it is a miss. If data is retrieved from cache, it's a hit.

As an example, the Cache::get call:

public function get($key, $default = null)
{
    if (is_array($key)) {
        return $this->many($key);
    }

    $value = $this->store->get($this->itemKey($key));

    if (is_null($value)) {
        $this->fireCacheEvent('missed', [$key]);

        $value = value($default);
    } else {
        $this->fireCacheEvent('hit', [$key, $value]);
    }

    return $value;
}

Upvotes: 2

Related Questions