Skip to content

Instantly share code, notes, and snippets.

@lezhnev74
Last active November 28, 2017 08:49
Show Gist options
  • Save lezhnev74/cfbaef98a4a2bdc6fc5e655c3746dc22 to your computer and use it in GitHub Desktop.
Save lezhnev74/cfbaef98a4a2bdc6fc5e655c3746dc22 to your computer and use it in GitHub Desktop.
Cache in a collection implementation
<?php
class MysqlCollection implements CollectionInterface
{
// .. other stuff
/** @var CacheInterface */
private $cache;
function findById(ID $id)
{
// this will make a cache key which makes sense only for the rest of life of this object
// if it is a singleton then any sequaential requests will not query actual db
$cache_key = $id."_".spl_object_hash($this);
if ($this->cache->has($cache_key)) {
$response = $this->cache->get($cache_key);
} else {
$response = $this->mysql->find($id);
$this->cache->set($cache_key, $response, "60sec");//will expire soon
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment