Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Weakmap Polyfill Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require benmorel/weakmap-polyfill
    

    No additional configuration is required—it works as a drop-in replacement.

  2. 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"
    
  3. Where to Look First

    • Source Code (if available)
    • WeakMap class docs (inline PHPDoc comments)
    • PHP’s native WeakMap behavior for expected API parity.

Implementation Patterns

Usage Patterns

  1. Caching Weak References Useful for storing objects that should not prevent garbage collection:

    $cache = new WeakMap();
    $cache->set($user, $user->getCachedData());
    
  2. Integration with Laravel

    • Service Container Binding:
      $app->bind(WeakMap::class, function () {
          return new WeakMap();
      });
      
    • Event Listeners/Jobs: Store transient data tied to objects (e.g., job metadata):
      $weakMap = app(WeakMap::class);
      $weakMap->set($job, ['attempts' => 0]);
      
  3. Leveraging with Collections Attach weak metadata to Eloquent models or collections:

    $user->weakMeta = new WeakMap();
    $user->weakMeta->set($user, ['last_visited' => now()]);
    

Workflows

  • Temporary Object State: Store ephemeral data (e.g., form validation errors per model instance).
  • Memory Optimization: Replace static caches or global arrays with weak references.
  • Testing: Mock weak references in unit tests without memory leaks.

Integration Tips

  • PSR-12 Compliance: Follow Laravel’s coding standards for consistency.
  • Type Safety: Use @var WeakMap in PHPDoc for IDE autocompletion.
  • Fallback Logic: Check for native WeakMap support first:
    $weakMap = class_exists('WeakMap') ? new \WeakMap() : new BenMorel\WeakMap\WeakMap();
    

Gotchas and Tips

Pitfalls

  1. Garbage Collection Behavior

    • Objects removed from the WeakMap do not trigger callbacks (unlike JavaScript’s WeakMap).
    • Debugging Tip: Use gc_collect_cycles() to force cleanup in tests:
      $weakMap->set($obj, 'data');
      $obj = null; // Detach reference
      gc_collect_cycles(); // Manual cleanup
      
  2. Serialization Issues

    • WeakMap instances cannot be serialized/deserialized (like native PHP WeakMap).
    • Workaround: Store only serializable data or avoid serialization entirely.
  3. PHP Version Quirks

    • Tested on PHP 7.4+; behavior may vary in older versions.
    • Tip: Add a runtime check:
      if (version_compare(PHP_VERSION, '7.4.0') < 0) {
          throw new RuntimeException('WeakMap requires PHP 7.4+');
      }
      

Debugging

  • Memory Leaks: Use 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
    
  • Key Validation: Ensure keys are objects (not primitives or resources).

Extension Points

  1. Custom Callbacks Extend the class to add lifecycle hooks (e.g., onKeyCollected):

    class MyWeakMap extends WeakMap {
        public function onKeyCollected(callable $callback) {
            // Implement custom logic
        }
    }
    
  2. Thread Safety

    • Not Thread-Safe: Avoid concurrent access in multi-threaded environments (e.g., PHP workers).
    • Workaround: Use a mutex or process isolation.
  3. Performance

    • Benchmark: Compare with native WeakMap in PHP 8.1+ (if available).
    • Tip: Prefer native WeakMap in PHP 8.1+ for better performance.

Config Quirks

  • No Configuration: The package is stateless; no config/weakmap.php exists.
  • Laravel Service Providers: Bind the class in AppServiceProvider if reused across contexts.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor