PHPSocialNetwork / phpfastcache

A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load. Well implemented, it can drops the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful.
https://www.phpfastcache.com
MIT License
2.36k stars 452 forks source link

Override set method for all drivers #828

Closed Awilum closed 3 years ago

Awilum commented 3 years ago

Hello!

I want to use such approach with time delta for all cache set execution in my project

// 1 Day 
$cacheTime = 24 * 60 * 60; 

// Time delta for cache regeneration
$delta = 60; 

cache()->set('blog', $blogCollection, ($cacheTime + rand(0, $delta)));
cache()->set('catalog', $catalogCollection, ($cacheTime + rand(0, $delta)));
cache()->set('testimonials', $testimonialsCollection, ($cacheTime + rand(0, $delta)));

I want to avoid cache invalidation at once with help of time delta.

Is it possible somehow to override the set method for all cache drivers to add this optional feature right in the set method?

Or it's only one way, to create my class, that will add this custom logic for default set method?

Geolim4 commented 3 years ago

Hello,

I don't understand what you're trying to do ? Are you working with the PSR6 interface or the PSR16 one ?

Anyway you can set the cache expiration of your cache item by setting it using expireAt(\Datetime) or expireAfter(\DateInterval|int) or

Awilum commented 3 years ago

I don't want to write this every time (when I am using Psr16 adapter)

->set('blog', $blogCollection, ($cacheTime + rand(0, $delta)));
->set('catalog', $catalogCollection, ($cacheTime + rand(0, $delta)));
->set('testimonials', $testimonialsCollection, ($cacheTime + rand(0, $delta)));

I want to write this

->set('blog', $blogCollection, $cacheTime);
->set('catalog', $catalogCollection, $cacheTime);
->set('testimonials', $testimonialsCollection, $cacheTime);

but delta time should be optional and comes underthehood of set method like this

function set($key, $data, $time)
{ 
  $delta = 60;
  ...->set($key, $data, ($time + rand(0, $delta))); 
}
Geolim4 commented 3 years ago

Oh I understand, in that case it's up to your own implementation.

Or you can try to alter the date with an event.

Using the onCacheSaveItem event would allow you to add your "delta".

Awilum commented 3 years ago

Thanks for your answer