Skip to content

Instantly share code, notes, and snippets.

@joelhinz
Created May 8, 2020 18:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joelhinz/ae4011010cac93a11741378617b477ea to your computer and use it in GitHub Desktop.
Save joelhinz/ae4011010cac93a11741378617b477ea to your computer and use it in GitHub Desktop.
<?php
namespace App\Some\Path;
class ShortTermMemory
{
private $store = [];
public function set($key, $value)
{
$this->store[$key] = $value;
}
public function get($key)
{
return $this->store[$key] ?? null;
}
public function has($key)
{
return isset($this->store[$key]);
}
public function remember($key, $callable)
{
if ($this->has($key)) {
return $this->get($key);
}
$result = $callable();
$this->set($key, $result);
return $result;
}
}
// and a helper function...
function stm($key = null, $default = null)
{
$stm = resolve(\App\Some\Path\ShortTermMemory::class); // I've bound this to a singleton in an SP
if (is_null($key)) {
return $stm;
}
if (is_null($default)) {
return $stm->get($key);
}
return $stm->has($key) ? $stm->get($key) : $default;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment