Dynamic Class Assignment

It is not unusual for an application to need to select the right class required to represent the configuration based on the data itself. For example, if the application is defining database connections then the type of database will require different connector classes. Hydration supports the dynamic creation of objects based on the data in the configuration via the with() method. with() takes a closure as an argument. The closure is passed the current value and Property and is expected to return the name of the class to be created and populated with the value.

class A implements Hydratable
{
    private static Hydrator $hydrator;
    public object $poly;

    public function hydrate($json, $options = []): bool
    {
        if (!isset(self::$hydrator)) {
            self::$hydrator = Hydrator::make(self::class)
                ->addProperty(
                    Property::make('date')
                        ->with(function ($value, Property $property) {
                            return '\\Some\\Namespace\\' . ucfirst(strtolower($value->type))
                                . 'Handler';
                        })
                );
        }
        return self::$hydrator->hydrate($this, $json, $options);
    }

}

$obj = new A();
$obj->hydrate('{"poly": {"type": "database", "name": "someName"}}');

This would cause Hydration to create a \Some\Namespace\DatabaseHandler object and assign it to $obj->poly.