composer require tonybogdanov/memoize:^2.0
class ClassUsingCaching {
use \TonyBogdanov\Memoize\Traits\MemoizeTrait;
public function getObjectLevelCachedThing() {
return $this->memoize( __METHOD__, function () {
return 'thing'; // heavy code that needs to run only once per object instance.
} );
}
}
You can also manually remove memoized values:
$object->unmemoize( 'key' );
You can even check if a memoized value exists without retrieving it (even if it's null
):
$object->isMemoized( 'key' );
class ClassUsingCaching {
use \TonyBogdanov\Memoize\Traits\MemoizeTrait;
public static function getClassLevelCachedThing() {
return static::memoizeStatic( __METHOD__, function () {
return 'thing'; // heavy code that needs to run only once per class.
} );
}
}
You can also manually remove memoized values:
StaticClass::unmemoizeStatic( 'key' );
You can even check if a memoized value exists without retrieving it (even if it's null
):
StaticClass::isMemoizedStatic( 'key' );
As of 2.3
you can access and manage the memoized values of foreign objects / classes as well.
// per-object
$this->memoizeForeign( $object, 'key', 'value' );
$this->unmemoizeForeign( $object, 'key' );
$this->isMemoizedForeign( $object, 'key' );
// per-class
StaticClass::memoizeStaticForeign( AnotherStaticClass::class, 'key', 'value' );
StaticClass::unmemoizeStaticForeign( AnotherStaticClass::class, 'key' );
StaticClass::isMemoizedStaticForeign( AnotherStaticClass::class, 'key' );
You can toggle memoization globally, which can be useful for testing:
Memoize::enable();
Memoize::disable();