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

Dict Laravel Package

php-standard-library/dict

Utility functions for working with PHP associative arrays (“dicts”): create, map, filter, and transform collections while preserving keys. Lightweight helpers from PHP Standard Library for cleaner, safer array manipulation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require php-standard-library/dict
    

    Add to composer.json under require or require-dev if needed.

  2. First Usage:

    use PHPStandardLibrary\Dict\Dict;
    
    // Create a new dictionary
    $dict = new Dict(['name' => 'John', 'age' => 30]);
    
    // Access values with safety
    $name = $dict->get('name'); // 'John'
    $country = $dict->get('country', 'USA'); // 'USA' (default)
    
  3. Key Methods:

    • get($key, $default = null): Safe key access.
    • set($key, $value): Set a key-value pair.
    • has($key): Check if a key exists.
    • merge(array $data): Merge another associative array.

First Use Case: Configuration Overrides

Replace raw array config overrides with Dict for clarity:

// Before
$config = config('app');
$theme = $config['theme'] ?? 'light';

// After
$configDict = new Dict(config('app'));
$theme = $configDict->get('theme', 'light');

// Merge overrides
$overrides = new Dict(['theme' => 'dark']);
$mergedConfig = $configDict->merge($overrides);

Implementation Patterns

Core Workflows

  1. Configuration Management:

    • Wrap Laravel’s config() output in Dict for type-safe access.
    • Use merge() to override settings dynamically:
      $appConfig = new Dict(config('app'));
      $envConfig = new Dict(['debug' => env('APP_DEBUG')]);
      $finalConfig = $appConfig->merge($envConfig);
      
  2. Request Data Handling:

    • Normalize request input into Dict for validation:
      use Illuminate\Http\Request;
      
      $requestDict = new Dict($request->all());
      $userInput = $requestDict->get('user', []);
      
  3. Dynamic Attributes:

    • Extend Eloquent models with Dict for metadata:
      // In User model
      public function attributesDict(): Dict
      {
          return new Dict($this->attributes);
      }
      
      // Usage
      $user = User::find(1);
      $theme = $user->attributesDict()->get('theme', 'default');
      
  4. Bulk Operations:

    • Chain methods for transformations:
      $data = new Dict(['users' => []]);
      $data->set('users', $users)
           ->merge(['active' => true])
           ->filter(fn ($value) => $value !== null);
      

Laravel Integration Tips

  1. Service Container Binding: Bind Dict globally for dependency injection:

    $app->bind(Dict::class, function () {
        return new Dict();
    });
    
  2. Request Macros: Add a toDict() method to Illuminate\Http\Request:

    Request::macro('toDict', function () {
        return new Dict($this->all());
    });
    
  3. Config File Structure: Use Dict in config/ files for nested defaults:

    // config/app.php
    return new Dict([
        'name' => 'Laravel',
        'timezone' => 'UTC',
        'defaults' => new Dict(['theme' => 'light']),
    ]);
    
  4. API Responses: Implement Arrayable/Jsonable for Dict:

    use Illuminate\Contracts\Support\Arrayable;
    
    class Dict implements Arrayable {
        public function toArray(): array {
            return $this->data;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Circular References:

    • Serializing nested Dict objects may cause infinite loops.
    • Fix: Add a maxDepth parameter to toArray():
      $dict->toArray(3); // Limit recursion depth
      
  2. Type Safety:

    • PHP 8.2+ typed properties aren’t enforced by default.
    • Tip: Use PHPStan to validate Dict usage:
      # phpstan.neon
      parameters:
          level: 8
          rules:
              PHPStandardLibrary\Dict\Dict::get: strict
      
  3. Performance:

    • Dict methods add slight overhead vs. raw arrays.
    • Benchmark: Use Dict only for complex operations; keep simple cases as arrays.
  4. Laravel-Specific Quirks:

    • Collections: Avoid mixing Dict and Collection unless necessary.
    • Service Container: Clear cached bindings if modifying Dict instances globally.

Debugging Tips

  1. Var Dump Formatting: Override __toString() for readable output:

    public function __toString(): string {
        return print_r($this->data, true);
    }
    
  2. Key Existence Checks: Use has() instead of isset() to avoid UndefinedIndex errors:

    if ($dict->has('key')) {
        // Safe to access
    }
    
  3. Default Values: Prefer get() with defaults over isset():

    // Before
    $value = $array['key'] ?? null;
    
    // After
    $value = $dict->get('key', null);
    

Extension Points

  1. Custom Accessors: Add domain-specific methods:

    $dict->set('user', $user)->getUserEmail(); // Custom logic
    
  2. Validation: Integrate with Laravel’s Validator:

    $dict->validate([
        'email' => 'required|email',
        'age' => 'integer|min:18',
    ]);
    
  3. Immutable Dict: Create a read-only subclass:

    class ImmutableDict extends Dict {
        public function set($key, $value) {
            throw new \RuntimeException('ImmutableDict is read-only');
        }
    }
    
  4. Laravel Mixins: Extend Eloquent models with Dict traits:

    use PHPStandardLibrary\Dict\Dict;
    
    trait Dictable {
        public function dict(): Dict {
            return new Dict($this->attributes);
        }
    }
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai