-
-
Save xeoncross/8712505 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 Lazy | |
* | |
* Allows for lazy initialization of object and class values. | |
* | |
* Example: | |
* | |
* class Test { | |
* use Lazy; | |
* | |
* // The name of the functions, i.e. 'x' and 'y', will be used as a key for the storage of initialized values | |
* | |
* function x() { return $this->lazy( function(){ return 'heavy-computation'; } ); } | |
* | |
* static function y() { return self::lazyStatic( function(){ return 'heavy-computation'; } ); } | |
* } | |
*/ | |
trait Lazy | |
{ | |
private $__lazilyInitialized = []; | |
private static $__lazilyInitializedStatic = []; | |
private static function __initializeLazily(&$storage, callable $initializer) | |
{ | |
$key = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3)[2]['function']; | |
if (!array_key_exists($key, $storage)) | |
{ | |
if (is_callable($initializer)) | |
$storage[$key] = call_user_func($initializer); | |
else | |
throw new RuntimeException('$initializer is not callable'); | |
} | |
return $storage[$key]; | |
} | |
/** | |
* @param callback $initializer | |
* @return mixed | |
*/ | |
protected function lazy(callable $initializer) | |
{ | |
return self::__initializeLazily($this->__lazilyInitialized, $initializer); | |
} | |
/** | |
* @param $initializer | |
* @return mixed | |
*/ | |
protected static function lazyStatic(callable $initializer) | |
{ | |
return self::__initializeLazily(self::$__lazilyInitializedStatic, $initializer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run the function when needed and then store the result so the closure is not called a second time.