Skip to content

Instantly share code, notes, and snippets.

@Donkfather
Created April 2, 2017 20:18
Show Gist options
  • Save Donkfather/8f07e833c492a35730438b1b0231898f to your computer and use it in GitHub Desktop.
Save Donkfather/8f07e833c492a35730438b1b0231898f to your computer and use it in GitHub Desktop.
Laravel Eloquent Cacheable Trait
<?php
/**
* Created by PhpStorm.
* User: donkfather
* Date: 02.04.2017
* Time: 23:04
*/
trait CachesAttributes {
/**
* The cached pocket
*
* @var array
* */
protected $loaded = [];
/**
* The attributes that should be cached
* @default all
* @var array
* */
protected $cacheable = ['*'];
/**
* Dynamically retrieve attributes on the model.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->rememberLoaded($key, function () use ($key)
{
return $this->getAttribute($key);
});
}
/**
* Dynamically set attributes on the model.
*
* @param string $key
* @param mixed $value
* @return void
*/
public function __set($key, $value)
{
$this->setAttribute($key, $value);
$this->setLoaded($key, $value);
}
/**
* @param $key
* @return mixed
*/
protected function getLoaded($key)
{
logger()->info("Cache hit for {$key} in " . class_basename($this) . ": {$this->loaded[$key]}");
return $this->hasLoaded($key) ? $this->loaded[$key] : null;
}
/**
* @param $key
* @return bool
*/
protected function hasLoaded($key)
{
return array_key_exists($key, $this->loaded) ? true : false;
}
/**
* @param $key
* @param \Closure $callback
* @return mixed
*/
protected function rememberLoaded($key, \Closure $callback)
{
return $this->hasLoaded($key) ? $this->getLoaded($key) : $this->setLoaded($key, $callback());
}
/**
* @param string $key
* @param \Closure|string $value
* @return mixed $value
*/
protected function setLoaded($key, $value)
{
$result = ( $value instanceof \Closure )?$value():$value;
if ($this->isCacheable($key))
{
logger()->info("Caching {$key} in " . class_basename($this) . ": {$result}");
return $this->loaded[$key] = $result;
}
return $result;
}
/**
* Determine if the given key is cacheable.
*
* @param string $key
* @return bool
*/
private function isCacheable($key)
{
return in_array($key, $this->getCacheable()) || $this->getCacheable() == ['*'];
}
/**
* Get the cacheable attributes for the model.
*
* @return array
*/
public function getCacheable()
{
return $this->cacheable;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment