Last active
November 28, 2017 08:49
-
-
Save lezhnev74/cfbaef98a4a2bdc6fc5e655c3746dc22 to your computer and use it in GitHub Desktop.
Cache in a collection implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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