battis / hydratable
Hydrate serialized objects with defaults and overrides
v0.1.1
2023-07-04 21:21 UTC
Requires
- php: >=7.3
Requires (Dev)
None
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
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);