Mixed-mode hydration strategy
Bilge opened this issue · 2 comments
Feature Request
Q | A |
---|---|
New Feature | yes |
RFC | no |
BC Break | no |
Summary
This library appears to support various single-mode hydration strategies for objects, including method hydration and property hydration, but does not seem to support any mixed-mode hydration strategies. For example, suppose I have an object with public properties but a few properties are also complimented by setters. I would like to use the setter if one exists, but if not, fall back to direct property assignment. Therefore I want a hydrator that uses method hydration first and falls back to property hydration if a setter is not available.
@Bilge
You can use the AggregateHydrator
. A short example:
class Album
{
public ?string $title;
private ?string $artist;
public function getArtist(): ?string
{
return $this->artist;
}
public function setArtist(?string $artist): void
{
$this->artist = $artist;
}
}
$hydrator = new Laminas\Hydrator\Aggregate\AggregateHydrator();
$hydrator->add(new Laminas\Hydrator\ObjectPropertyHydrator());
$hydrator->add(new Laminas\Hydrator\ClassMethodsHydrator());
$album = new Album();
// Hydrate
$hydrator->hydrate(['title' => "Let's Dance", 'artist' => 'David Bowie'], $album);
var_dump($album->title); // 'Let's Dance'
var_dump($album->getArtist()); // 'David Bowie'
// Extract
$data = $hydrator->extract($album);
var_dump($data);
/*
array(2) {
'title' =>
string(11) "Let's Dance"
'artist' =>
string(11) "David Bowie"
}
*/
More informations can be found in the documentation: https://docs.laminas.dev/laminas-hydrator/v4/aggregate/
Very good answer, thanks.