This package adds cacheability to method calls. It requires the Laravel framework.
composer require vagento/cacheable
Trait: Cacheable - Method Cacheability
Add the \Vagento\Cacheable\Traits\Cacheable
trait to any class that needs the results of a method call to be cached.
use Vagento\Cacheable\Traits\Cacheable;
class MyClass
{
use Cacheable; // Add this trait
public function myMethod()
{
// Big computational task
return $bigData;
}
}
Now you can call your method with the 'Cached' suffix like this:
$myClass = new MyClass();
$result = $myClass->myMethodCached();
Optional parameters can be passed before the method call (Can be chained):
$myClass = new MyClass();
// Optional: Cache usage, will toggle caching on or off
// Default: true
$myClass->setCacheUsage(false);
// Optional: Laravel cache tags @see https://laravel.com/docs/8.x/cache#cache-tags
// Default: null
$myClass->setCacheTags('my-method-tag');
// Optional: Time to live
// Default: null
$myClass->setTtl(60);
$myClass->setTtl(Carbon::now()->addMinutes(30)->toDateTime());
// Chaining
$result = $myClass->setCacheUsage(true)->setCacheTags(['method', 'something-else'])->setTtl(60)->myMethodCached();
For IDE support you can add the @method
annotation to your class like this:
/**
* @method array myMethodCached()
*/
class MyClass
{
use Cacheable;
public function myMethod(): array
{
// Big computational task
return $bigData;
}
}
Give a ⭐️ if this project helped you!
Copyright © 2021 Valentin Wotschel.
This project is MIT licensed.