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.
Install the package:
composer require php-standard-library/dict
Basic usage:
use Dict\Dict;
$dict = new Dict(['name' => 'John', 'age' => 30]);
echo $dict->get('name'); // "John"
$dict->set('age', 31); // Updates value
First Laravel use case:
Replace raw array config access with Dict:
$configDict = new Dict(config('app'));
$timezone = $configDict->get('timezone', 'UTC');
Dict class in src/Dict.php for core methods (get, set, has, merge, etc.).// 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);
use Illuminate\Http\Request;
public function store(Request $request) {
$input = new Dict($request->all());
$validated = $input->only(['name', 'email'])->filter();
// ...
}
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);
}
}
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');
}
}
Dict globally for config:
$app->singleton(Dict::class, fn() => new Dict(config('app')));
Illuminate\Http\Request to return Dict:
Request::macro('toDict', function() {
return new Dict($this->all());
});
Arrayable/Jsonable:
class Dict implements \JsonSerializable {
public function toArray(): array { /* ... */ }
public function toJson($options = 0): string { /* ... */ }
}
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'));
Circular References:
toArray() if Dict contains self-referential data.maxDepth parameter or use iterator_to_array() with IteratorIterator::LIMIT_DEPTH.Type Safety:
// phpstan.config.php
return [
'parameters' => [
'level' => 8,
'checkPropertyTypeInNew' => true,
],
];
Laravel Integration Gaps:
Arrayable/Jsonable.class Dict implements \JsonSerializable {
public function toArray(): array { return $this->all(); }
public function jsonSerialize(): array { return $this->toArray(); }
}
Performance Overhead:
Dict methods are ~10-15% slower than raw arrays for hot paths.__toString() for readable dumps:
public function __toString(): string {
return print_r($this->all(), true);
}
tap() for debugging:
$dict->tap(fn($d) => Log::debug('Dict state:', $d->all()));
Custom Accessors:
$dict->setAccessor('full_name', fn($dict) => "{$dict->get('first')} {$dict->get('last')}");
echo $dict->get('full_name'); // "John Doe"
Validation:
Integrate with Laravel’s Validator:
use Illuminate\Support\Facades\Validator;
$dict = new Dict($request->all());
$validator = Validator::make($dict->all(), [
'email' => 'required|email',
]);
Immutable Dict: Create a read-only subclass:
class ImmutableDict extends Dict {
public function set($key, $value): void {
throw new \RuntimeException('ImmutableDict is read-only');
}
}
Dict as a singleton if it holds mutable state (e.g., request data).Dict for cached config, but serialize carefully:
Cache::put('config', $dict->toArray(), $ttl);
Dict in unit tests:
$mockDict = Mockery::mock(Dict::class)->makePartial();
$mockDict->shouldReceive('get')->with('key')->andReturn('value');
get() with defaults instead of isset():
// Bad
$value = $array['key'] ?? $default;
// Good
$value = $dict->get('key', $default);
$dict->get('user.address.city'); // "New York"
Or use get() with a callback:
$dict->get('user', fn($userDict) => $userDict->get('address.city'));
How can I help you explore Laravel packages today?