Abivia Hydration

Powerful Object Hydration and Encoding

Hydration gives your application the ability to initialize class structures from configuration or generic structures files while validating user-generated configurations. Encoding features can simplify stored configurations by eliminating default values, so users only need to deal with what they need.

Hydration supports processing source data in JSON, YAML or generic (stdClass) objects.

Key capabilities of Hydration include:

  • Selective conversion of object structures into arrays.
  • Extraction of object properties to create associative arrays.
  • Dynamic polymorphic object creation based on input data.
  • Validation and transformation of user input.
  • Property name mapping allows user-friendly property names that map to application property names.

Installation

Install with composer: require abivia/hydration.

Basic Use

Add the Hydratable interface to your class, create a basic implementation of hydrate() that includes public properties and pass the configuration in to hydrate().

use Abivia\Hydration\Hydrator;
use Abivia\Hydration\Hydratable;

class MyClass implements JsonSerializable, Hydratable
 {
    private static Hydrator $hydrator;
    public $foo;
    public $bar;
    protected $bat;

    public function hydrate($json, $options = []): bool {
        if (!isset(self::$hydrator)) {
            self::$hydrator = Hydrator::make(self::class);
        }
        return self::$hydrator->hydrate($this, $json, $options);
    }

    public function jsonSerialize()
    {
        return self::$hydrator->encode($this);
    }
}

$myObject = new MyClass();
$myObject->hydrate('{"bar": "This is bar", "foo": "This is foo"}');

// This will throw an error since $bat is not public:
$myObject->hydrate('{"bat": true}');
In this case the Hydrator is implicitly bound to the properties of the host class by supplying it as the parameter to make(), which defaults to adding only public properties. The second argument to make() allows the selection of any combination of public, protected, and private properties. Hydration uses Reflection to populate non-public properties.

In typical use, behaviour of the Hydrator will be defined through Property objects that tell Hydration how they should be encoded and decoded.

Code, Issues, Support

Source code is hosted on GitHub at https://github.com/abivia/hydration with CI running on GitLab at https://gitlab.com/abivia/hydration.

Issues, questions, and pull requests can be submitted via GitHub at https://github.com/abivia/hydration/issues.

Contributions and feedback are welcomed.