Immutable Value Objects for PHP 8.3+ inspired by spatie/laravel-data, created by Davey Shafik.
Bag helps you create immutable value objects. It's a great way to encapsulate data within your application.
Bag prioritizes immutability and type safety with built-in validation and data casting.
Value objects should be used in place of regular arrays, allowing you enforce type safety and immutability.
- Immutable & Strongly typed
- Value casting — both input and output
- Collection support
- Composable — nest Bag value objects and collections
- Built-in validation
Note
Bag is framework-agnostic, but it works great with Laravel. Bag uses standard Laravel Collections and Validation. In addition, it will automatically inject Bag\Bag
value objects into your controllers with validation.
Bag requires PHP 8.3+, and supports Laravel 11.x.
You can install the package via composer:
composer require dshafik/bag
To create a basic Value Object, extend the Bag\Bag
class and define your properties in the constructor:
use Bag\Bag;
readonly class MyValue extends Bag {
public function __construct(
public string $name,
public int $age,
) {
}
}
To create a new instance of your Value Object, call the ::from()
method:
$value = MyValue::from([
'name' => 'Davey Shafik',
'age' => 40,
]);
Full documentation can be found here.