laminas/laminas-hydrator
Laminas Hydrator provides flexible strategies to hydrate and extract data between objects and arrays. Supports reflection, class methods, naming strategies, and custom hydrators, making it easy to map entities, DTOs, and forms cleanly across your application.
INFO: New Feature Available since version 4.8.0
MISSING: Installation Requirements Enumerations require PHP version 8.1 or higher.
The BackedEnumStrategy provides bidirectional conversion between strings
or integers and Backed Enums.
The code examples below will use the following backed enum, representing a genre of music:
enum Genre: string
{
case Pop = 'pop';
case Blues = 'blues';
case Jazz = 'jazz';
}
The following code example shows standalone usage without adding the strategy to a hydrator.
Create the strategy passing the class name of the enum it will hydrate and extract:
$strategy = new Laminas\Hydrator\Strategy\BackedEnumStrategy(Genre::class);
$hydrated = $strategy->hydrate('blues', null);
var_dump($hydrated); // enum Genre::Blues : string("blues");
$extracted = $strategy->extract(Genre::Pop);
var_dump($extracted); // string(3) "pop"
The following example demonstrates hydration for a class with a property.
An example class which represents an album with a music genre:
class Album
{
private ?Genre $genre;
public function __construct(?Genre $genre = null)
{
$this->genre = $genre;
}
public function getGenre() : Genre
{
return $this->genre;
}
}
Create a hydrator and add the BackedEnumStrategy as a strategy:
$hydrator = new Laminas\Hydrator\ReflectionHydrator();
$hydrator->addStrategy(
'genre',
new Laminas\Hydrator\Strategy\BackedEnumStrategy(Genre::class)
);
Create an instance of the example class and hydrate data:
$album = new Album();
$hydrator->hydrate(['genre' => 'jazz'], $album);
echo $album->getGenre()->value; // "jazz"
$extracted = $hydrator->extract($album);
echo $extracted['genre']; // "jazz"
How can I help you explore Laravel packages today?