Skip to content

Commit

Permalink
Identifier for mixed data and cache hit handling
Browse files Browse the repository at this point in the history
- Adds new function to create identifier of mixed data
- Allowes mixed data "with" cache
- Caches only if not already cached
- Touch cached files on use to handle cache item hit
  • Loading branch information
jtkDvlp committed Dec 16, 2018
1 parent e36b220 commit 56ed37c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
22 changes: 19 additions & 3 deletions src/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function wrap($func)
return function() use ($func)
{
$arguments = func_get_args();
$identifier = sha1(serialize($arguments));
$identifier = $this->identifierOf($arguments);

return $this->get($identifier) ?:
$this->set($identifier,
Expand All @@ -45,14 +45,30 @@ public function wrap($func)

/**
* @param callback $func
* @param string $identifier
* @param string|mixed $identifier
* @return mixed
*/
public function with($func, $identifier) {
$identifier = is_string($identifier) ?
$identifier :
$this->identifierOf($identifier);

$cachedValue = $this->get($identifier, null);
$alreadyCached = null !== $cachedValue;
$funcResult = call_user_func($func, $cachedValue);
$this->set($identifier, $cachedValue);

if(false === $alreadyCached) {
$this->set($identifier, $cachedValue);
}

return $funcResult;
}

/**
* @param mixed $data
* @return string
*/
public function identifierOf($data) {
return sha1(serialize($data));
}
}
30 changes: 17 additions & 13 deletions src/FileCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,31 @@ public function __destruct()

/**
* @param string $identifier
* @param mixed $default
* @return mixed
* @return boolean
*/
public function get($identifier, $default = null)
public function has($identifier)
{
return $this->inMemory->get($identifier, null) ?:
$this->inMemory->set($identifier,
(unserialize(
file_get_contents(
$this->determineItemPath($identifier))) ?:
$default));
return $this->inMemory->has($identifier) ||
file_exists($this->determineItemPath($identifier));
}

/**
* @param string $identifier
* @return boolean
* @param mixed $default
* @return mixed
*/
public function has($identifier)
public function get($identifier, $default = null)
{
return $this->inMemory->has($identifier) ||
file_exists($this->determineItemPath($identifier));
$filepath = $this->determineItemPath($identifier);

$cached = $this->inMemory->get($identifier, null) ?:
$this->inMemory->set($identifier,
(unserialize(
file_get_contents($filepath)) ?:
$default));

touch($filepath);
return $cached;
}

/**
Expand Down

0 comments on commit 56ed37c

Please sign in to comment.