This recipe is the converse of the Creating an array to object hydrator recipe. In this case, we need to pull values from object properties and return an associative array where the key will be the column name.
Application\Generic\Hydrator\GetSet class defined in the previous recipe:namespace Application\Generic\Hydrator;
class GetSet
{
// code
}hydrate() method defined in the previous recipe, we define an extract() method, which takes an object as an argument. The logic is similar to that used with hydrate(), except this time we're searching for getXXX() methods. Again, preg_match() is used to match the method prefix and its suffix, which is subsequently assumed to be the array key:public static function extract($object)
{
$array = array();
$class = get_class($object);
$methodList = get_class_methods($class);
foreach ($methodList as $method) {
preg_match('/^(get)(.*?)$/i', $method, $matches);
$prefix = $matches[1] ?? '';
$key = $matches[2] ?? '';
$key = strtolower(substr($key, 0, 1)) . substr($key, 1);
if ($prefix == 'get') {
$array[$key] = $object->$method();
}
}
return $array;
}
}Define a calling program called chap_11_object_to_array.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, define an instance of Person, setting values for its properties:
$obj = new Person();
$obj->setFirstName('Li\'lAbner');
$obj->setLastName('Yokum');
$obj->setAddress('1DirtStreet');
$obj->setCity('Dogpatch');
$obj->setStateProv('Kentucky');
$obj->setPostalCode('12345');
$obj->setCountry('USA');Finally, call the new extract() method in a static manner:
$a = GetSet::extract($obj); var_dump($a);
The output is shown in the following screenshot:
