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.
Hydrator class that is able to use getters and setters. For this illustration we will use Application\Generic\Hydrator\GetSet:namespace Application\Generic\Hydrator;
class GetSet
{
// code
}hydrate() method, which takes both an array and an object as arguments. It then calls the setXXX() methods on the object to populate it with values from the array. We use get_class() to determine the object's class, and then get_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);
$methodList = get_class_methods($class);
foreach ($methodList as $method) {
preg_match('/^(set)(.*?)$/i', $method, $matches);
$prefix = $matches[1] ?? '';
$key = $matches[2] ?? '';
$key = strtolower(substr($key, 0, 1)) . substr($key, 1);
if ($prefix == 'set' && !empty($array[$key])) {
$object->$method($array[$key]);
}
}
return $object;
}To demonstrate how the array to hydrator object is used, first define the Application\Generic\Hydrator\GetSet class as described in the How to do it... section. Next, define an entity class that can be used to test the concept. For the purposes of this illustration, create a Application\Entity\Person class, with the appropriate properties and methods. Be sure to define getters and setters for all properties. Not all such methods are shown here:
namespace Application\Entity;
class Person
{
protected $firstName = '';
protected $lastName = '';
protected $address = '';
protected $city = '';
protected $stateProv = '';
protected $postalCode = '';
protected $country = '';
public function getFirstName()
{
return $this->firstName;
}
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
// etc.
}You can now create a calling program called chap_11_array_to_object.php, which sets up autoloading, and uses the appropriate classes:
<?php require __DIR__ . '/../Application/Autoload/Loader.php'; Application\Autoload\Loader::init(__DIR__ . '/..'); use Application\Entity\Person; use Application\Generic\Hydrator\GetSet;
Next, you can define a test array with values that will be added to a new Person instance:
$a['firstName'] = 'Li\'l Abner'; $a['lastName'] = 'Yokum'; $a['address'] = '1 Dirt Street'; $a['city'] = 'Dogpatch'; $a['stateProv'] = 'Kentucky'; $a['postalCode']= '12345'; $a['country'] = 'USA';
You can now call hydrate() and extract() in a static manner:
$b = GetSet::hydrate($a, new Person()); var_dump($b);
The results are shown in the following screenshot:
