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**
   ```bash
   composer require php-standard-library/dict:^6.1

No additional configuration is required—just autoload the package.

  1. First Use Case: Configuration Bag Replace raw arrays with a Dict for explicit intent, now with immutable operations by default in v6.1:

    use PhpStandardLibrary\Dict;
    
    $config = new Dict([
        'app.name' => 'MyApp',
        'app.debug' => false,
    ]);
    
    // Access values with type-like safety
    $name = $config->get('app.name'); // string
    $debug = $config->get('app.debug', false); // bool (default fallback)
    
    // NEW: Immutable by default (v6.1)
    $updated = $config->set('app.debug', true); // Returns new Dict
    
  2. Where to Look First

    • Core Methods: get(), set(), has(), merge(), update() (Note: merge() and update() now return new instances unless explicitly mutated.)
    • Iteration: each(), keys(), values() (compatible with foreach)
    • Defaults: Built-in fallback logic for missing keys + new setDefault() for persistent defaults.
    • NEW: Dict::fromArray() helper for quick conversion:
      $dict = Dict::fromArray(['key' => 'value']);
      

Implementation Patterns

1. Replacing Raw Arrays

Before (v6.0):

$data = new Dict(['user' => ['name' => 'Alice']]);
$name = $data->get('user.name');

After (v6.1):

$data = Dict::fromArray(['user' => ['name' => 'Alice']]);
$name = $data->get('user.name'); // Immutable by default

2. Configuration Management

Use Dict to manage nested app/config structures with explicit mutability:

$config = Dict::fromArray([
    'database' => ['connections' => ['mysql' => ['host' => 'localhost']]],
]);

// NEW: Immutable merge (returns new Dict)
$updatedConfig = $config->merge(['database.connections.mysql.host' => 'db.example.com']);

// Mutate in-place (explicit)
$config->mergeInto($this, ['database.connections.mysql.port' => 3306]);

3. Attribute Stores

Model dynamic attributes with type safety and immutability:

$user = Dict::fromArray(['id' => 1, 'metadata' => []]);
$userWithColor = $user->set('metadata.color', 'blue'); // New instance

// Bulk update (immutable)
$userWithMetadata = $user->update(['metadata.size' => 'large']);

4. Integration with Laravel

  • Service Providers: Leverage immutability for thread safety:
    $this->app->singleton('config.bag', fn() => Dict::fromArray(config('app')));
    
  • Request Data: Sanitize input with immutable filtering:
    $input = Dict::fromArray(request()->all());
    $validated = $input->filter(fn($val) => !is_null($val)); // New instance
    

5. Collection-Like Workflows

Leverage iteration methods for consistency (unchanged):

$dict = Dict::fromArray(['a' => 1, 'b' => 2]);
foreach ($dict->keys() as $key) {
    echo $dict->get($key); // 1, 2
}

6. NEW: Helper Methods (v6.1)

  • Dict::fromArray(): Quick conversion from arrays.
  • setDefault(): Persistent defaults for missing keys:
    $dict = Dict::fromArray(['app' => ['name' => 'MyApp']]);
    $dict->setDefault('app.debug', false);
    $dict->get('app.debug'); // false (now stored)
    
  • mergeInto()/updateInto(): Explicit mutable operations.

Gotchas and Tips

Pitfalls

  1. Immutable Operations (NEW in v6.1)

    • Methods like set(), merge(), and update() return new Dict instances by default.
    • Fix: Use ->setInto($this, ...) or ->mergeInto($this, ...) to mutate in-place.
    • Example:
      $dict = Dict::fromArray(['key' => 'value']);
      $dict = $dict->set('new.key', 'new_value'); // New instance
      $dict->setInto($this, 'mutated.key', 'mutated_value'); // Modifies $dict
      
  2. Nested Dot Notation (Unchanged)

    • Keys like user.address.city are treated as nested paths.
    • Fix: Use Dict objects for nested structures or flatten keys:
      $dict->set('user.address', Dict::fromArray(['city' => 'NY']));
      
  3. Default Fallbacks (Clarified)

    • get() with defaults does not modify the Dict. Use setDefault() for persistent defaults:
      $dict->setDefault('fallback', 'default_value');
      $dict->get('nonexistent'); // 'default_value' (now stored)
      

Debugging Tips

  • Inspect Structure: Use toArray() for debugging (unchanged):
    dd($dict->toArray()); // Convert to plain array
    
  • Key Validation: Check for typos with has() before get() (unchanged):
    if (!$dict->has('user.email')) {
        throw new \InvalidArgumentException("Missing 'user.email'");
    }
    
  • NEW: Use Dict::fromArray() for quick debugging:
    $debugDict = Dict::fromArray($arrayData);
    dd($debugDict->toArray());
    

Extension Points

  1. Custom Defaults (Enhanced) Override default behavior for specific keys with setDefaultResolver:

    $dict->setDefaultResolver(fn($key) => "default_$key");
    $dict->get('missing'); // 'default_missing'
    
  2. Type Safety (Unchanged) Use PHP 8.2+ typed properties with Dict:

    class UserDict extends Dict {
        public function getName(): string {
            return $this->get('name', '');
        }
    }
    
  3. Laravel Integration (Updated)

    • Service Container: Bind immutable Dict for thread safety:
      $this->app->singleton('config.dict', fn() => Dict::fromArray(config()->all()));
      
    • Form Requests: Validate nested Dict structures (unchanged):
      $this->validate($dict->toArray(), ['user.email' => 'required|email']);
      

Performance Notes (Updated)

  • Memory: Dict adds minimal overhead (~10% for small arrays).
  • Immutability: New instances on mutation may increase memory usage in loops. Optimization: Use mergeInto()/updateInto() for in-place mutations in performance-critical paths.
  • Large Data: For >10k keys, consider ArrayObject or raw arrays.

Config Quirks (Updated)

  • Dot Notation Parsing: Avoid keys with .. or leading/trailing dots (e.g., .hidden).
  • Case Sensitivity: Keys are case-sensitive ('Key''key').
  • Serialization: Implements JsonSerializable and ArrayAccess (unchanged).
  • NEW: fromArray() helper avoids manual instantiation:
    $dict = Dict::fromArray($array); // Preferred over `new Dict($array)`
    

Breaking Changes (v6.1)

  1. Immutable by Default:
    • set(), merge(), update(), and filter() now return new instances.
    • Migration: Replace $dict->set(...) with $dict = $dict->set(...) or use ->setInto($this, ...).
  2. Deprecated Methods:
    • Dict::create() is deprecated; use Dict::fromArray() instead.
  3. New Helpers:
    • setDefault(), mergeInto(), and updateInto() are added for explicit mutability.

NO_UPDATE_NEEDED would **not** apply here due to the breaking changes and new features in v6.1.1. The above is the fully updated assessment.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4