dshafik / bag
A comprehensive immutable value objects implementation
Installs: 1 210
Dependents: 1
Suggesters: 0
Security: 0
Stars: 74
Watchers: 4
Forks: 7
Open Issues: 5
Requires
- php: ^8.2|^8.3|^8.4
- brick/money: ^0.8.1 || ^0.9.0 || ^0.10.0
- illuminate/collections: ^10|^11
- illuminate/database: ^10|^11
- illuminate/support: ^10|^11
- illuminate/validation: ^10|^11
- league/pipeline: ^1.0
- nette/php-generator: ^4.1
- prinsfrank/standards: ^3.8
- ramsey/uuid: ^4.7
Requires (Dev)
- captainhook/captainhook-phar: ^5.23
- captainhook/hook-installer: ^1.0
- larastan/larastan: ^2.0
- laravel/pint: ^1.15
- laravel/prompts: ^0.1.25 || ^0.2.0 || ^0.3.0
- orchestra/pest-plugin-testbench: ^2.0|^3.0
- pestphp/pest: ^2.0|^3.0
- pestphp/pest-plugin-faker: ^2.0|^3.0
- pestphp/pest-plugin-type-coverage: ^2.0|^3.0
- ramsey/conventional-commits: ^1.5.1
- roave/security-advisories: dev-latest
- symfony/var-dumper: *
This package is auto-updated.
Last update: 2024-12-16 14:10:13 UTC
README
Bag
Immutable Value Objects for PHP 8.3+ inspired by spatie/laravel-data, created by Davey Shafik.
Introduction
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.
When to use Value Objects
Value objects should be used in place of regular arrays, allowing you enforce type safety and immutability.
Features
- 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.
Requirements
Bag requires PHP 8.3+, and supports Laravel 11.x.
Installation
You can install the package via composer:
composer require dshafik/bag
Usage
Creating a Value Object
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, ) { } }
Instantiating a Value Object
To create a new instance of your Value Object, call the ::from()
method:
$value = MyValue::from([ 'name' => 'Davey Shafik', 'age' => 40, ]);
Documentation
Full documentation can be found here.