Created
November 7, 2016 14:46
-
-
Save mlebkowski/d203ba1bfb0fe8e54adfed5217d32fa9 to your computer and use it in GitHub Desktop.
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 | |
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