avris/bag
avris/bag is a small Laravel/PHP utility package providing a “bag” style container for working with grouped values and simple data access. Handy for passing around structured payloads, storing arbitrary attributes, and keeping collections of data lightweight.
Installation Add the package via Composer:
composer require avris/bag
No additional configuration is required—it’s a drop-in replacement for PHP arrays with enhanced functionality.
First Use Case
Replace a standard PHP array with a Bag instance:
use Avris\Bag\Bag;
$bag = new Bag(['name' => 'John', 'age' => 30]);
echo $bag->name; // Access properties directly
echo $bag['age']; // Fallback to array syntax
Where to Look First
Bag.php for magic methods (__get, __set, __isset, __unset).Property Access Over Arrays Prefer dot notation for readability:
$bag = new Bag(['user' => ['name' => 'Alice']]);
echo $bag->user->name; // 'Alice' (nested access)
Fluent Method Chaining
Use put() and merge() for dynamic data manipulation:
$bag->put('status', 'active')->merge(['role' => 'admin']);
Laravel-Specific Workflows
$this->app->bind(Bag::class, function () {
return new Bag(request()->all());
});
@foreach($bag->items as $item)
{{ $item->name }}
@endforeach
Data Validation
Combine with Laravel’s Validator:
$validator = Validator::make($bag->toArray(), [
'name' => 'required|string',
'age' => 'integer|min:18',
]);
Bag in controllers, services, or DTOs to enforce structured access.
public function store(Request $request) {
$data = new Bag($request->validated());
// ...
}
Bag to JSON with json_encode($bag) (implements JsonSerializable).Bag in PHPUnit for predictable property access:
$this->partialMock(Bag::class, ['__get']);
Nested Property Access Limits
$bag->a->b->c) may fail if intermediate keys are missing.data_get() or data_set() for safe access:
$value = $bag->get('a.b.c', null);
Type Juggling
Bag casts keys/values to strings (like arrays), which may cause unexpected behavior with objects.array_walk for type enforcement.Serialization Quirks
serialize()/unserialize() may not preserve object state.toArray() + json_encode() for persistence.$bag->method fails, verify no custom __get/__call conflicts exist.declare(strict_types=1); to catch type-related issues early.Bag to add domain-specific methods:
class UserBag extends Bag {
public function isAdmin() {
return $this->role === 'admin';
}
}
__set to trigger events:
protected function __set($key, $value) {
event(new BagUpdated($this, $key, $value));
parent::__set($key, $value);
}
Bag class globally:
$this->app->bind(Bag::class, function () {
return new UserBag();
});
Bag for large datasets (memory overhead vs. native arrays).How can I help you explore Laravel packages today?