benmorel/weakmap-polyfill
Polyfill for PHP WeakMap, providing weakly-referenced key/value storage for older PHP versions. Store data associated with objects without preventing garbage collection. Useful for caches, metadata, and object maps in libraries and frameworks.
Installation Add the package via Composer:
composer require benmorel/weakmap-polyfill
No additional configuration is required—it works as a drop-in replacement.
First Use Case
Replace native WeakMap usage with the polyfill:
use BenMorel\WeakMap\WeakMap;
$weakMap = new WeakMap();
$obj = new stdClass();
$weakMap->set($obj, 'value');
echo $weakMap->get($obj); // Outputs: "value"
Where to Look First
WeakMap class docs (inline PHPDoc comments)WeakMap behavior for expected API parity.Caching Weak References Useful for storing objects that should not prevent garbage collection:
$cache = new WeakMap();
$cache->set($user, $user->getCachedData());
Integration with Laravel
$app->bind(WeakMap::class, function () {
return new WeakMap();
});
$weakMap = app(WeakMap::class);
$weakMap->set($job, ['attempts' => 0]);
Leveraging with Collections Attach weak metadata to Eloquent models or collections:
$user->weakMeta = new WeakMap();
$user->weakMeta->set($user, ['last_visited' => now()]);
@var WeakMap in PHPDoc for IDE autocompletion.WeakMap support first:
$weakMap = class_exists('WeakMap') ? new \WeakMap() : new BenMorel\WeakMap\WeakMap();
Garbage Collection Behavior
WeakMap do not trigger callbacks (unlike JavaScript’s WeakMap).gc_collect_cycles() to force cleanup in tests:
$weakMap->set($obj, 'data');
$obj = null; // Detach reference
gc_collect_cycles(); // Manual cleanup
Serialization Issues
WeakMap instances cannot be serialized/deserialized (like native PHP WeakMap).PHP Version Quirks
if (version_compare(PHP_VERSION, '7.4.0') < 0) {
throw new RuntimeException('WeakMap requires PHP 7.4+');
}
memory_get_usage() to verify objects are collected:
$before = memory_get_usage();
$weakMap->set($obj, 'data');
$obj = null;
gc_collect_cycles();
$after = memory_get_usage();
echo $before - $after; // Should reflect memory freed
Custom Callbacks
Extend the class to add lifecycle hooks (e.g., onKeyCollected):
class MyWeakMap extends WeakMap {
public function onKeyCollected(callable $callback) {
// Implement custom logic
}
}
Thread Safety
Performance
WeakMap in PHP 8.1+ (if available).WeakMap in PHP 8.1+ for better performance.config/weakmap.php exists.AppServiceProvider if reused across contexts.How can I help you explore Laravel packages today?