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.
## Getting Started
### Minimal Setup
1. **Installation**
```bash
composer require php-standard-library/dict:^6.1
No additional configuration is required—just autoload the package.
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
Where to Look First
get(), set(), has(), merge(), update()
(Note: merge() and update() now return new instances unless explicitly mutated.)each(), keys(), values() (compatible with foreach)setDefault() for persistent defaults.Dict::fromArray() helper for quick conversion:
$dict = Dict::fromArray(['key' => 'value']);
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
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]);
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']);
$this->app->singleton('config.bag', fn() => Dict::fromArray(config('app')));
$input = Dict::fromArray(request()->all());
$validated = $input->filter(fn($val) => !is_null($val)); // New instance
Leverage iteration methods for consistency (unchanged):
$dict = Dict::fromArray(['a' => 1, 'b' => 2]);
foreach ($dict->keys() as $key) {
echo $dict->get($key); // 1, 2
}
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.Immutable Operations (NEW in v6.1)
set(), merge(), and update() return new Dict instances by default.->setInto($this, ...) or ->mergeInto($this, ...) to mutate in-place.$dict = Dict::fromArray(['key' => 'value']);
$dict = $dict->set('new.key', 'new_value'); // New instance
$dict->setInto($this, 'mutated.key', 'mutated_value'); // Modifies $dict
Nested Dot Notation (Unchanged)
user.address.city are treated as nested paths.Dict objects for nested structures or flatten keys:
$dict->set('user.address', Dict::fromArray(['city' => 'NY']));
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)
toArray() for debugging (unchanged):
dd($dict->toArray()); // Convert to plain array
has() before get() (unchanged):
if (!$dict->has('user.email')) {
throw new \InvalidArgumentException("Missing 'user.email'");
}
Dict::fromArray() for quick debugging:
$debugDict = Dict::fromArray($arrayData);
dd($debugDict->toArray());
Custom Defaults (Enhanced)
Override default behavior for specific keys with setDefaultResolver:
$dict->setDefaultResolver(fn($key) => "default_$key");
$dict->get('missing'); // 'default_missing'
Type Safety (Unchanged)
Use PHP 8.2+ typed properties with Dict:
class UserDict extends Dict {
public function getName(): string {
return $this->get('name', '');
}
}
Laravel Integration (Updated)
Dict for thread safety:
$this->app->singleton('config.dict', fn() => Dict::fromArray(config()->all()));
Dict structures (unchanged):
$this->validate($dict->toArray(), ['user.email' => 'required|email']);
Dict adds minimal overhead (~10% for small arrays).mergeInto()/updateInto() for in-place mutations in performance-critical paths.ArrayObject or raw arrays... or leading/trailing dots (e.g., .hidden).'Key' ≠ 'key').JsonSerializable and ArrayAccess (unchanged).fromArray() helper avoids manual instantiation:
$dict = Dict::fromArray($array); // Preferred over `new Dict($array)`
set(), merge(), update(), and filter() now return new instances.$dict->set(...) with $dict = $dict->set(...) or use ->setInto($this, ...).Dict::create() is deprecated; use Dict::fromArray() instead.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.
How can I help you explore Laravel packages today?