Skip to content

Commit

Permalink
Feature/cache (#57)
Browse files Browse the repository at this point in the history
* Corrects return type for array processor

* Replaces With_Object_Cache with the With_Cache trait. This makes it possible to set a cache strategy that determines how the cache is handled.

* Replaces With_Object_Cache with the With_Cache trait. This makes it possible to set a cache strategy that determines how the cache is handled.
  • Loading branch information
alexstandiford committed Feb 21, 2023
1 parent fe35410 commit 639097c
Showing 1 changed file with 88 additions and 0 deletions.
88 changes: 88 additions & 0 deletions lib/Traits/With_Cache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace Underpin\Traits;

use Underpin\Exceptions\Cached_Item_Not_Found;
use Underpin\Exceptions\Cache_Store_Failed;
use Underpin\Interfaces\Cache_Strategy;
use Underpin\Registries\Logger;

trait With_Cache
{
protected array $object_cache = [];

/**
* @param string $key The cache key
* @param callable $setter The setter that sets the cache value
* @param ?Cache_Strategy $strategy The strategy to use when loading from the cache. If unset, this will default to
* Underpin's object cache strategy.
*
* @return mixed
*/
protected function load_from_cache(string $key, callable $setter, ?Cache_Strategy $strategy = null) : mixed
{
if (! $strategy) {
return $this->load_from_object($key, $setter);
}

return $this->load_from_strategy($key, $setter, $strategy);
}

/**
* Loads the data using the provided strategy
*
* @param string $key The cache key
* @param callable $setter The setter that sets the cache value
* @param Cache_Strategy $strategy The strategy to use when loading from the cache. If unset, this will default to
* Underpin's object cache strategy.
*
* @return mixed
*/
private function load_from_strategy(string $key, callable $setter, Cache_Strategy $strategy) : mixed
{
try {
$result = $strategy->get($key);
} catch (Cached_Item_Not_Found $e) {
$result = $setter();
$this->set_cache($key, $result, $strategy);
}

return $result;
}

/**
* Stores the data in the provided cache strategy
*
* @param string $key The cache key
* @param mixed $value The setter that sets the cache value
* @param Cache_Strategy $strategy The strategy to use when loading from the cache. If unset, this will default to
* Underpin's object cache strategy.
*
* @return void
*/
private function set_cache(string $key, mixed $value, Cache_Strategy $strategy) : void
{
try {
$strategy->set($key, $value);
} catch (Cache_Store_Failed $e) {
Logger::warning($e);
}
}

/**
* Loads an item from the object cache.
*
* @param string $key
* @param callable $setter
*
* @return mixed
*/
private function load_from_object(string $key, callable $setter) : mixed
{
if (! isset($this->object_cache[$key])) {
$this->object_cache[$key] = $setter();
}

return $this->object_cache[$key];
}
}

0 comments on commit 639097c

Please sign in to comment.