Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save proudlygeek/88835c43aab6266e1e76 to your computer and use it in GitHub Desktop.

Select an option

Save proudlygeek/88835c43aab6266e1e76 to your computer and use it in GitHub Desktop.
PHP Cache Trait
<?php
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];
}
}
class MyModel {
use Cachable;
public function getSlowQueryResults()
{
// Long operation
return "[Result] Very long result...\n";
}
public function foo()
{
print_r($this->cache);
}
}
$model = new MyModel();
echo $model->cached('getSlowQueryResults', []);
echo $model->cached('getSlowQueryResults', []);
$model->foo();
$model->getSlowQueryResult();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment