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.
Available since version 3.1.0
DateTimeImmutableFormatterStrategy provides bidirectional conversion between
strings and DateTimeImmutable instances.
The strategy uses DateTimeFormatterStrategy for conversion where the
input and output formats
can be set.
The following code example shows standalone usage without adding the strategy to a hydrator.
Create the strategy and set the input and output formats
via the DateTimeFormatterStrategy.
$strategy = new Laminas\Hydrator\Strategy\DateTimeImmutableFormatterStrategy(
new Laminas\Hydrator\Strategy\DateTimeFormatterStrategy('Y-m-d')
);
$hydrated = $strategy->hydrate('2020-07-01');
var_dump($hydrated instanceof DateTimeImmutable); // true
$extracted = $strategy->extract(
DateTimeImmutable::createFromFormat('Y-m-d', '2020-07-01')
);
echo $extracted // '2020-07-01'
The following example demonstrates hydration for a class with a property.
An example class which represents a music album with a release date:
class Album
{
private ?DateTimeImmutable $releaseDate;
public function __construct(?DateTimeImmutable $releaseDate = null)
{
$this->releaseDate = $releaseDate;
}
public function getReleaseDate() : ?DateTimeImmutable
{
return $this->releaseDate;
}
}
Create a hydrator and add DateTimeImmutableFormatterStrategy as strategy:
$hydrator = new Laminas\Hydrator\ReflectionHydrator();
$hydrator->addStrategy(
'releaseDate',
new Laminas\Hydrator\Strategy\DateTimeImmutableFormatterStrategy(
new Laminas\Hydrator\Strategy\DateTimeFormatterStrategy('Y-m-d')
)
);
Create an instance of the example class and hydrate data:
$album = new Album();
$hydrator->hydrate(['releaseDate' => '2020-07-01'], $album);
var_dump($album->getReleaseDate() instanceof DateTimeImmutable); // true
$extracted = $hydrator->extract($album);
echo $extracted; // '2020-07-01'
How can I help you explore Laravel packages today?