tonybogdanov / memoize
Object & class-level in-memory caching
Installs: 4 269
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 2
Forks: 0
Open Issues: 1
Requires
- php-64bit: ^7.4|^8.1
Requires (Dev)
- phpunit/phpunit: ^9.5
README
Installation
composer require tonybogdanov/memoize:^2.0
Usage
Per-Object Memoization
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' );
Per-Class Memoization
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' );
Foreign Objects
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' );
Toggle Memoization
You can toggle memoization globally, which can be useful for testing:
Memoize::enable(); Memoize::disable();