Skip to content

Instantly share code, notes, and snippets.

@abdumu
Created March 4, 2018 11:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdumu/301e89826e50e49712b81ceced0b1060 to your computer and use it in GitHub Desktop.
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()
<?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);
}
}
@abdumu
Copy link
Author

abdumu commented Aug 19, 2018

How to use it:

Copy the trait to app folder or any subfolder there

import the trait in your Model class,

class Post extends Model
{
   use Cacheable;

   public function anyFunction() 
   {
       //your code ...
   }
}

then you can call any functions from that class with suffix Cached, like

$post->anyFunctionCached()

can works with static methods too

Post::anyFunctionCached()

The method will be cached for 60 minutes, to change the time add static variables

class Post extends Model
{
   use Cacheable;

   protected static $cacheableMinutes = 3600;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment