battis/hydratable

Hydrate serialized objects with defaults and overrides

v0.1.1 2023-07-04 21:21 UTC

This package is auto-updated.

Last update: 2024-11-03 21:54:03 UTC


README

Latest Version codecov

Hydrate serialized objects with defaults and overrides

This is meant to make it easier to take DRY arguments and hydrate them based on preset defaults.

Install

composer require battis/hydratable

Use

This can either be added as a trait to a class or as an invokable class.

use Battis\Hydratable\Hydratable;

class MyObject
{
    use Hydratable;

    private static $DEFAULTS = [
      'foo' => 'bar',
      'argle' => 'bargle'
    ]

    private $options;

    public function __construct(array $params = [])
    {
        $this->options = $this->hydrate($params, self::$DEFAULTS);
    }
}

One could then instantiate an instance of MyObject:

$o = new MyObject(['baz' => 123, 'argle' = 'BaRgLe']);

/*
$o->options = [
    'foo' => 'bar',
    'baz' => 123,
    'argle' => 'BaRgLe'
]
*/

Alternatively, we could simply instantiate Hydrate and use it as a one-off:

$hydrate = new Battis\Hydratable\Hydrate();
$options = $hydrate($params, $defaults);