Getters and Setters

A setting in a configuration file need not directly correspond to a property in the hydrated class. Hydration can pass values to getter and setter methods in the class to provide more sophisticated hydration and encoding. Since Hydration uses Reflection to access these methods, they can have private or protected scopes.

Setters

By default, Hydration simply assigns the configured value to a property. However, since a configuration setting might not correspond directly to a class property, the application may want to perform the assignment via a setter method. This is achieved via setter(). The setter takes the name of the class method that will perform the assignment. An optional second argument controls passing of the Property to the setter. The default is to pass the Property.

Class A implements Hydratable
{
    private string $foo;
    private bool $fooExists;

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

    public function setFoo(string $value, Property $property)
    {
        $this->foo = 'Some\\Prefix\\' . ucfirst(strtolower($foo));
        $this->fooExists = class_exists($this->foo);
    }

}

Hydration will pass the property value and (unless disabled) the Property definition into the setter. The Property can be used to access the hydration context.

Getters

Similar to setters, the application might want to use a getter when encoding. getter() allows the application to name a getter method in the class when retrieving it for encoding. getter() accepts an optional argument that controls passing of the Property to the getter. This defaults to true.

Class B implements Hydratable
{
    private string $email;
    private string $name;

    public function hydrate($json): bool
    {
        if (!isset(self::$hydrator)) {
            self::$hydrator = Hydrator::make()
                ->addProperty(
                    Property::make('contact')
                        ->getter('getContact', false)
                )
                ->bind(self::class);
        }
        return self::$hydrator->hydrate($this, $json);
    }

    public function getContact()
    {
        return "$this->name <$this->email>";
    }

}