Created
June 10, 2020 22:16
-
-
Save jonasraoni/07e94293f1bb09ec44b9fff6a33d562c to your computer and use it in GitHub Desktop.
Class to retrieve values lazily from a callback
This file contains 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 | |
//+ Jonas Raoni Soares Silva | |
//@ http://raoni.org | |
class Lazy { | |
private $_cache; | |
private $_handler; | |
public function __construct(callable $handler) | |
{ | |
$this->_handler = $handler; | |
} | |
public function __invoke() | |
{ | |
$key = $this->_hash(func_get_args()); | |
return array_key_exists($key, $this->_cache ?? []) ? $this->_cache[$key] : ($this->_cache[$key] = ($this->_handler)(...func_get_args())); | |
} | |
public function reset(): void | |
{ | |
$this->_cache = null; | |
} | |
public function isCached(): bool | |
{ | |
return array_key_exists($this->_hash(func_get_args()), $this->_cache ?? []); | |
} | |
private function _hash($data): string | |
{ | |
return serialize($data); | |
} | |
} | |
$lazy = new Lazy(function ($data){ | |
echo "Lazy run $data\n"; | |
}); | |
$lazy('A'); | |
$lazy('A'); | |
$lazy('A'); | |
$lazy('B'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment