Created
March 4, 2018 11:42
-
-
Save abdumu/301e89826e50e49712b81ceced0b1060 to your computer and use it in GitHub Desktop.
Cacheable Trait for Laravel Model Class for methods, request any method after adding the trait with 'Cached' as methodNameCached()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App; | |
use Illuminate\Support\Facades\Cache; | |
trait Cacheable | |
{ | |
public function __call($methodName, $arguments) | |
{ | |
if (ends_with($methodName, 'Cached')) { | |
$method = str_before($methodName, 'Cached'); | |
$key = "cachable::{$methodName}::".md5(serialize($arguments)); | |
return Cache::remember($key, static::$cacheableMinutes ?? 60, function () use($method, $arguments) { | |
$this->$method(...$arguments); | |
}); | |
} | |
return parent::__call($methodName, $arguments); | |
} | |
public static function __callStatic($methodName, $arguments) | |
{ | |
if (ends_with($methodName, 'Cached')) { | |
$method = str_before($methodName, 'Cached'); | |
$key = "cachable::{$methodName}::" . md5(serialize($arguments)); | |
return Cache::remember($key, static::$cacheableMinutes ?? 60, function () use ($method, $arguments) { | |
return static::$method(...$arguments); | |
}); | |
} | |
return parent::__callStatic($methodName, $arguments); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to use it:
Copy the trait to app folder or any subfolder there
import the trait in your Model class,
then you can call any functions from that class with suffix
Cached
, likecan works with static methods too
The method will be cached for 60 minutes, to change the time add static variables