Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Created March 18, 2015 15:18
Show Gist options
  • Select an option

  • Save proudlygeek/9579c2ec693d689e9036 to your computer and use it in GitHub Desktop.

Select an option

Save proudlygeek/9579c2ec693d689e9036 to your computer and use it in GitHub Desktop.
<?php
// You can use an abstract class as well
trait Cachable {
private $cache = [];
public function cached($method, $args) {
echo "[Cache] Called $method\n";
if (!isset($this->cache[$method])) {
echo "[Cache] Saving method in cache\n";
$this->cache[$method] = $this->$method($args);
}
echo $this->cache[$method];
}
}
abstract class Model {
public function __call($method, $args)
{
$origMethod = preg_replace('/cached/', '', $method);
if (preg_match('/cached.*/', $method) &&
array_key_exists('Cachable', class_uses(get_class($this)))) {
return $this->cached($origMethod, $args);
} else {
return $this->$origMethod($args);
}
}
}
class MyModel extends Model {
use Cachable;
public function getSlowQueryResults()
{
// Long operation
return "[Result] Very long result...\n";
}
}
$model = new MyModel();
echo $model->cachedGetSlowQueryResults();
echo $model->cachedGetSlowQueryResults();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment