Created
May 8, 2020 18:36
-
-
Save joelhinz/ae4011010cac93a11741378617b477ea to your computer and use it in GitHub Desktop.
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 | |
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