Property Shortcuts
Adding multiple Properties with similar settings
In practice, many properties have identical configurations. Rather than duplicate these,
Hydrator::addProperties()
simplifies the creation of similar properties.
addProperties()
takes two arguments. The first is a list of properties. Elements of this list can
be:
- the property name
- an array of
[sourceName, targetName]
for mapping an external name to a class property - a Property object.
The second argument is a list of calls to Property methods: ['methodname' => argument]
. If the
argument parameter is an array, the array is unpacked and passed to the method.
Class A implements Hydratable
{
//...
public function hydrate($json, $options = []): bool
{
if (!isset(self::$hydrator)) {
self::$hydrator = Hydrator::make()
->addProperties(
[
'example',
['hyphenated-example', 'hyphenatedExample']
],
[
'require' => true,
'validate' => function ($value) {
return is_numeric($value);
}
]
)
->bind(self::class);
}
return self::$hydrator->hydrate($this, $json, $options);
}
}
Configuring a Property from an array
The Property::set()
method takes a list of calls to Property methods:
['methodname' => argument]
. If the argument parameter is an array, the array is unpacked and
passed to the method.
$property = Property::make('example')
->set(
[
'require' => true,
'validate' => function ($value) {
return is_numeric($value);
}
]
);