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.
Installation:
composer require php-standard-library/dict
Add to composer.json under require or require-dev if needed.
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)
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.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);
Configuration Management:
config() output in Dict for type-safe access.merge() to override settings dynamically:
$appConfig = new Dict(config('app'));
$envConfig = new Dict(['debug' => env('APP_DEBUG')]);
$finalConfig = $appConfig->merge($envConfig);
Request Data Handling:
Dict for validation:
use Illuminate\Http\Request;
$requestDict = new Dict($request->all());
$userInput = $requestDict->get('user', []);
Dynamic Attributes:
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');
Bulk Operations:
$data = new Dict(['users' => []]);
$data->set('users', $users)
->merge(['active' => true])
->filter(fn ($value) => $value !== null);
Service Container Binding:
Bind Dict globally for dependency injection:
$app->bind(Dict::class, function () {
return new Dict();
});
Request Macros:
Add a toDict() method to Illuminate\Http\Request:
Request::macro('toDict', function () {
return new Dict($this->all());
});
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']),
]);
API Responses:
Implement Arrayable/Jsonable for Dict:
use Illuminate\Contracts\Support\Arrayable;
class Dict implements Arrayable {
public function toArray(): array {
return $this->data;
}
}
Circular References:
Dict objects may cause infinite loops.maxDepth parameter to toArray():
$dict->toArray(3); // Limit recursion depth
Type Safety:
Dict usage:
# phpstan.neon
parameters:
level: 8
rules:
PHPStandardLibrary\Dict\Dict::get: strict
Performance:
Dict methods add slight overhead vs. raw arrays.Dict only for complex operations; keep simple cases as arrays.Laravel-Specific Quirks:
Dict and Collection unless necessary.Dict instances globally.Var Dump Formatting:
Override __toString() for readable output:
public function __toString(): string {
return print_r($this->data, true);
}
Key Existence Checks:
Use has() instead of isset() to avoid UndefinedIndex errors:
if ($dict->has('key')) {
// Safe to access
}
Default Values:
Prefer get() with defaults over isset():
// Before
$value = $array['key'] ?? null;
// After
$value = $dict->get('key', null);
Custom Accessors: Add domain-specific methods:
$dict->set('user', $user)->getUserEmail(); // Custom logic
Validation:
Integrate with Laravel’s Validator:
$dict->validate([
'email' => 'required|email',
'age' => 'integer|min:18',
]);
Immutable Dict: Create a read-only subclass:
class ImmutableDict extends Dict {
public function set($key, $value) {
throw new \RuntimeException('ImmutableDict is read-only');
}
}
Laravel Mixins:
Extend Eloquent models with Dict traits:
use PHPStandardLibrary\Dict\Dict;
trait Dictable {
public function dict(): Dict {
return new Dict($this->attributes);
}
}
How can I help you explore Laravel packages today?