Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Forked from meglio/Lazy.php
Created January 30, 2014 16:27
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 xeoncross/8712505 to your computer and use it in GitHub Desktop.
Save xeoncross/8712505 to your computer and use it in GitHub Desktop.
<?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);
}
}
@xeoncross
Copy link
Author

Run the function when needed and then store the result so the closure is not called a second time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment