The Hydrator pattern is a variation of the Data Transfer Object design pattern. Its design principle is quite simple: moving data from one place to another. In this illustration, we will define classes to move data from an array to an object.
First, we define a
Hydrator
class that is able to use getters and setters. For this illustration we will useApplication\Generic\Hydrator\GetSet
:namespace Application\Generic\Hydrator; class GetSet { // code }
Next, we define a
hydrate()
method, which takes both an array and an object as arguments. It then calls thesetXXX()
methods on the object to populate it with values from the array. We useget_class()
to determine the object's class, and thenget_class_methods()
to get a list of all methods.preg_match()
is used to match the method prefix and its suffix, which is subsequently assumed to be the array key:public static function hydrate(array $array, $object) { $class = get_class($object); ...