Skip to content

Instantly share code, notes, and snippets.

@mlebkowski
Created November 7, 2016 14:46
Show Gist options
  • Save mlebkowski/d203ba1bfb0fe8e54adfed5217d32fa9 to your computer and use it in GitHub Desktop.
Save mlebkowski/d203ba1bfb0fe8e54adfed5217d32fa9 to your computer and use it in GitHub Desktop.
<?php
Trait OnceTrait {
private $once = [];
protected function once($callback, ...$arguments)
{
$hash = $this->hashOnceMethod(func_get_args());
if (false === isset($this->once[$hash])) {
$result = call_user_func_array($callback, $arguments);
$this->once[$hash] = $result;
}
return $this->once[$hash];
}
protected function hashOnceMethod(array $arguments)
{
return md5(serialize(array_map(function ($value) {
if (is_array($value)) {
return $this->hashOnceMethod($value);
}
if (is_object($value)) {
return spl_object_hash($value);
}
return $value;
}, $arguments)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment