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

Weak Types Laravel Package

boson-php/weak-types

Weak-types helpers for the Boson PHP ecosystem. Install via Composer and use alongside Boson to build desktop apps with configuration, windows, webviews, bindings, scripts, and request interception—see the Boson docs for guides and APIs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require boson-php/weak-types
    

    Ensure your project uses PHP 8.4+ (check composer.json and server compatibility).

  2. First Use Case: Convert a loosely typed array (e.g., API response) into a weakly typed structure:

    use Boson\WeakTypes\WeakMap;
    
    $data = ['user' => ['name' => 'John', 'roles' => ['admin']]];
    $weakMap = WeakMap::from($data);
    
    // Access values (weakly typed)
    $name = $weakMap->get('user.name'); // Returns 'John' (string)
    $roles = $weakMap->get('user.roles'); // Returns ['admin'] (array)
    
  3. Where to Look First:

    • WeakMap: For key-value pairs with weak references (e.g., caching, dynamic configs).
    • WeakSet: For unique weak references (e.g., tracking objects without strong holds).
    • WeakType: For custom weakly typed objects (advanced use cases).
    • Documentation: Boson PHP Docs (focus on "Weak Structures" section).

Implementation Patterns

Usage Patterns

  1. Dynamic Data Handling:

    • Replace rigid array/object structures in API wrappers or config-as-code:
      $config = WeakMap::from([
          'database' => [
              'default' => 'mysql',
              'connections' => ['mysql' => ['host' => 'localhost']],
          ],
      ]);
      
    • Laravel Integration: Use in config/app.php or service providers for hot-reloadable configs.
  2. Memory-Sensitive Operations:

    • Caching: Store large objects in WeakMap to avoid memory leaks:
      $cache = new WeakMap();
      $cache->set('large_object', $expensiveToLoadObject);
      
    • Event Listeners: Clean up listeners after execution:
      Event::listen(function () use (&$weakSet) {
          $weakSet->add($this); // Listener will be GC’d after event
      });
      
  3. Hybrid Type Systems:

    • Mix weak and strong types in DTOs or plugins:
      class PluginConfig {
          public WeakMap $settings;
          public string $name;
      
          public function __construct() {
              $this->settings = WeakMap::from([]);
          }
      }
      
  4. Laravel-Specific Workflows:

    • Service Container: Register weak structures as singletons:
      $app->singleton(WeakMap::class, function () {
          return new WeakMap(['default' => 'value']);
      });
      
    • HTTP Requests: Deserialize payloads weakly:
      use Illuminate\Http\Request;
      use Boson\WeakTypes\WeakType;
      
      $request->merge(WeakType::from($request->all()));
      

Integration Tips

  1. Avoid Breaking Strong Types:

    • Use weak structures only in specific contexts (e.g., caching layers, plugins).
    • Example: Create a WeakCacheStore class to wrap Illuminate\Cache\Store.
  2. Leverage Laravel’s Events:

    • Attach weak structures to event payloads for short-lived data:
      event(new UserProcessed($user, WeakMap::from(['metadata' => $data])));
      
  3. Testing:

    • Mock weak structures with custom test doubles:
      $weakMap = Mockery::mock(WeakMap::class);
      $weakMap->shouldReceive('get')->andReturn('mocked_value');
      
  4. Performance Tuning:

    • Benchmark weak vs. strong structures for large datasets:
      $weakMap = WeakMap::from(range(1, 1000000));
      $strongArray = range(1, 1000000);
      // Compare memory usage with `memory_get_usage()`.
      

Gotchas and Tips

Pitfalls

  1. Unexpected Object Collection:

    • Weak references are garbage-collected when no strong references exist:
      $weakMap = new WeakMap();
      $obj = new stdClass();
      $weakMap->set('key', $obj);
      unset($obj); // $weakMap->get('key') may return null!
      
    • Fix: Keep a strong reference if the object must persist.
  2. Circular References:

    • Weak structures won’t break circular references—PHP’s GC handles this, but it may delay collection:
      $a = new stdClass(); $a->b = $b;
      $b = new stdClass(); $b->a = $a;
      $weakMap->set('a', $a); // Both objects may linger.
      
    • Fix: Use WeakSet for unique weak references or manual cleanup.
  3. Laravel Cache Driver Issues:

    • Some drivers (e.g., file, database) ignore weak references during serialization:
      Cache::put('weak_key', $weakMap); // May store a serialized copy!
      
    • Fix: Use custom cache stores (e.g., Redis or Memcached) that support weak references.
  4. Type Confusion:

    • Weak structures don’t enforce types—values can change unexpectedly:
      $weakMap->set('age', '25'); // Stored as string
      $age = $weakMap->get('age') + 1; // TypeError!
      
    • Fix: Validate types explicitly or use WeakType for stricter contracts.
  5. Debugging Challenges:

    • var_dump() or dd() may not show weak references as expected:
      dd($weakMap->get('key')); // May output `null` even if the object exists.
      
    • Fix: Use WeakType::inspect() for debugging or log strong references.

Debugging Tips

  1. Check for Strong References:

    $obj = new stdClass();
    $weakMap->set('obj', $obj);
    var_dump($weakMap->get('obj')); // null if no strong references
    var_dump($obj); // Still exists if referenced elsewhere
    
  2. Force Collection:

    $weakMap->clear(); // Manually trigger GC
    gc_collect_cycles(); // Force garbage collection (PHP 8.1+)
    
  3. Log Weak Structure State:

    $weakMap->onCollection(function () {
        Log::debug('WeakMap collected keys: ' . implode(',', $this->keys()));
    });
    

Config Quirks

  1. PHP 8.4+ Features:

    • The package may rely on PHP 8.4 attributes or new typed properties. Ensure your composer.json enforces:
      "config": {
          "platform": {
              "php": "8.4.0"
          }
      }
      
  2. Laravel Service Provider Conflicts:

    • If using multiple boson-php packages, alias classes explicitly:
      use Boson\WeakTypes\WeakMap as BosonWeakMap;
      
  3. Environment-Specific Behavior:

    • Weak references behave differently under different PHP SAPIs (CLI vs. FPM). Test in production-like environments.

Extension Points

  1. Custom Weak Structures:

    • Extend WeakType to create domain-specific weak types:
      class WeakUser extends WeakType {
          public function getName(): string {
              return $this->get('name');
          }
      }
      
  2. Laravel Service Providers:

    • Bind weak structures to the container with conditional logic:
      $app->when(WeakMap::class)
          ->needs('$config')
          ->give(fn () => config('weak_types.defaults'));
      
  3. Event Listeners for Weak Structures:

    • Listen for collection events to log or migrate data:
      $weakMap->onCollection(function (array $collectedKeys) {
          // Trigger a backup or fallback
      });
      
  4. Integration with Laravel Collections:

    • Convert Illuminate\Support\Collection to weak structures:
      $weakMap = WeakMap::from(collect($array)->toArray());
      
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
andydefer/laravel-cluster
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