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. Install the package:

    composer require php-standard-library/dict
    
  2. Basic usage:

    use Dict\Dict;
    
    $dict = new Dict(['name' => 'John', 'age' => 30]);
    echo $dict->get('name'); // "John"
    $dict->set('age', 31);  // Updates value
    
  3. First Laravel use case: Replace raw array config access with Dict:

    $configDict = new Dict(config('app'));
    $timezone = $configDict->get('timezone', 'UTC');
    

Where to Look First

  • Documentation for API reference.
  • Dict class in src/Dict.php for core methods (get, set, has, merge, etc.).
  • Laravel integration examples in the assessment-tpm.md (config, requests, Eloquent).

Implementation Patterns

Core Workflows

1. Configuration Management

// Replace raw config access
$appConfig = new Dict(config('app'));
$theme = $appConfig->get('theme', 'light');

// Merge overrides (e.g., environment-specific)
$envOverrides = new Dict(['theme' => 'dark']);
$mergedConfig = $appConfig->merge($envOverrides);

2. Request Data Handling

use Illuminate\Http\Request;

public function store(Request $request) {
    $input = new Dict($request->all());
    $validated = $input->only(['name', 'email'])->filter();
    // ...
}

3. Eloquent Model Attributes

use Dict\Dict;

class User extends Model {
    protected $attributesDict;

    public function __construct(array $attributes = []) {
        parent::__construct($attributes);
        $this->attributesDict = new Dict($attributes);
    }

    public function getDynamicAttribute($key) {
        return $this->attributesDict->get($key);
    }
}

4. Service Class State

class UserService {
    protected Dict $userData;

    public function __construct() {
        $this->userData = new Dict();
    }

    public function setName(string $name): void {
        $this->userData->set('name', $name);
    }

    public function getName(): ?string {
        return $this->userData->get('name');
    }
}

Integration Tips

  • Laravel Service Container: Bind Dict globally for config:
    $app->singleton(Dict::class, fn() => new Dict(config('app')));
    
  • Request Macros: Extend Illuminate\Http\Request to return Dict:
    Request::macro('toDict', function() {
        return new Dict($this->all());
    });
    
  • API Responses: Implement Arrayable/Jsonable:
    class Dict implements \JsonSerializable {
        public function toArray(): array { /* ... */ }
        public function toJson($options = 0): string { /* ... */ }
    }
    

Chaining and Collections

Leverage Dict with Laravel’s Collection for hybrid workflows:

$users = User::all()->map(fn($user) => new Dict($user->toArray()));
$activeUsers = $users->filter(fn($dict) => $dict->get('is_active'));

Gotchas and Tips

Pitfalls

  1. Circular References:

    • Issue: Infinite recursion in toArray() if Dict contains self-referential data.
    • Fix: Add a maxDepth parameter or use iterator_to_array() with IteratorIterator::LIMIT_DEPTH.
  2. Type Safety:

    • Issue: No native PHP 8.2+ generics; runtime type checks still needed.
    • Fix: Use PHPStan to enforce type hints:
      // phpstan.config.php
      return [
          'parameters' => [
              'level' => 8,
              'checkPropertyTypeInNew' => true,
          ],
      ];
      
  3. Laravel Integration Gaps:

    • Issue: No built-in support for Arrayable/Jsonable.
    • Fix: Implement manually:
      class Dict implements \JsonSerializable {
          public function toArray(): array { return $this->all(); }
          public function jsonSerialize(): array { return $this->toArray(); }
      }
      
  4. Performance Overhead:

    • Issue: Dict methods are ~10-15% slower than raw arrays for hot paths.
    • Fix: Benchmark critical paths; use raw arrays for performance-sensitive code.

Debugging Tips

  • Var Dump: Override __toString() for readable dumps:
    public function __toString(): string {
        return print_r($this->all(), true);
    }
    
  • Logging: Use tap() for debugging:
    $dict->tap(fn($d) => Log::debug('Dict state:', $d->all()));
    

Extension Points

  1. Custom Accessors:

    $dict->setAccessor('full_name', fn($dict) => "{$dict->get('first')} {$dict->get('last')}");
    echo $dict->get('full_name'); // "John Doe"
    
  2. Validation: Integrate with Laravel’s Validator:

    use Illuminate\Support\Facades\Validator;
    
    $dict = new Dict($request->all());
    $validator = Validator::make($dict->all(), [
        'email' => 'required|email',
    ]);
    
  3. Immutable Dict: Create a read-only subclass:

    class ImmutableDict extends Dict {
        public function set($key, $value): void {
            throw new \RuntimeException('ImmutableDict is read-only');
        }
    }
    

Laravel-Specific Quirks

  • Service Container Binding: Avoid binding Dict as a singleton if it holds mutable state (e.g., request data).
  • Caching: Use Dict for cached config, but serialize carefully:
    Cache::put('config', $dict->toArray(), $ttl);
    
  • Testing: Mock Dict in unit tests:
    $mockDict = Mockery::mock(Dict::class)->makePartial();
    $mockDict->shouldReceive('get')->with('key')->andReturn('value');
    

Configuration Quirks

  • Default Values: Use get() with defaults instead of isset():
    // Bad
    $value = $array['key'] ?? $default;
    
    // Good
    $value = $dict->get('key', $default);
    
  • Nested Dicts: Access nested keys with dot notation:
    $dict->get('user.address.city'); // "New York"
    
    Or use get() with a callback:
    $dict->get('user', fn($userDict) => $userDict->get('address.city'));
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata