somnambulist / attribute-model
Provides a base model that uses an internal array of attributes with type casting
Installs: 3 136
Dependents: 2
Suggesters: 0
Security: 0
Stars: 0
Watchers: 4
Forks: 0
Open Issues: 0
Requires
- php: >=8.1
- ext-json: *
- pragmarx/ia-str: ^7.0
Requires (Dev)
- phpunit/phpunit: ^10.5
- somnambulist/collection: ^5.0
- somnambulist/domain: ^6.0
- symfony/var-dumper: ^6.4
README
A sort-of-kind-of ActiveModel type'ish base for Models that rely on an array of attributes. Includes a type-casting sub-system for casting attributes to values. Extracted from read-models.
The focus is for creating read-only Model representations for use in presentation layers. This library is used by somnambulist/read-models and api-client.
Requirements
- PHP 8.1+
- pragmarx/ia-str
Installation
Install using composer, or checkout / pull the files from github.com.
- composer require somnambulist/attribute-model
Usage
Extend to a model e.g. User; or implement into a base model and add extra functionality. Use attribute casting if needed before passing attributes into the model.
<?php use Somnambulist\Components\AttributeModel\AbstractModel; use Somnambulist\Components\AttributeModel\AttributeCaster; use Somnambulist\Components\AttributeModel\TypeCasters\AreaCaster; use Somnambulist\Components\AttributeModel\TypeCasters\MoneyCaster; class User extends AbstractModel { } $caster = new AttributeCaster([ new AreaCaster(), new MoneyCaster(), ]); $attrs = []; $user = new User($caster->cast($attrs, ['area' => 'area', 'money' => 'money',]));
Built-in Casters
The following casters are built-in and are largely configurable by type or attribute name(s):
Many of the casters accept alternative attribute names for matching and type overrides. Suitable defaults are provided where appropriate (e.g.: json, json_array, json_collection).
More casters can be added by implementing the interface and attaching to the AttributeCaster
.
An existing caster can be re-used on another type by calling $caster->extend(<type>, [new, types, here])
.
The configuration of the caster cannot be changed; it adds extra type keys that the caster will
respond to.
Tests
PHPUnit 9+ is used for testing. Run tests via vendor/bin/phpunit
.