Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Created June 10, 2020 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasraoni/07e94293f1bb09ec44b9fff6a33d562c to your computer and use it in GitHub Desktop.
Save jonasraoni/07e94293f1bb09ec44b9fff6a33d562c to your computer and use it in GitHub Desktop.
Class to retrieve values lazily from a callback
<?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