Skip to content

Basic Usage

Creating a Value Object

To create a new Value Object, extend the Bag\Bag class and define your properties in the constructor:

php
use Bag\Bag;

readonly class MyValue extends Bag {
    public function __construct(
        public string $name,
        public int $age,
    ) {
    }
}

Instantiating a Value Object

To create a new instance of your Value Object, call the ::from() method:

php
$value = MyValue::from([
    'name' => 'Davey Shafik',
    'age' => 40,
]);

Type Casting

Bag will cast all values to their defined type automatically for all scalar types, as well as the following:

  • Bag objects
  • \Bag\Collection and \Illuminate\Support\Collection objects
  • \DateTimeInterface objects will be cast using standard PHP Date/Time formats
    • This includes \DateTime, \DateTimeImmutable, \Carbon\Carbon and \Carbon\CarbonImmutable
  • Enums

TIP

We recommend using \Carbon\CarbonImmutable for all date times.

Modifying a Value Object

Value Objects are immutable, so you cannot change their properties directly. Instead, you can create a new instance with the updated values using the Bag->with() method:

php
$value = MyValue::from([
    'name' => 'Davey Shafik',
    'age' => 40,
]);

$newValue = $value->with(age: 41);

dump($newValue->toArray()); // ['name' => 'Davey Shafik', 'age' => 41]

You can pass either named arguments, or an array or Collection of key-value pairs to the Bag->with() method.

Made with 🦁💖🏳️‍🌈 by Davey Shafik.