Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Created Jun 10, 2020
Embed
What would you like to do?
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