Creating an array to object hydrator

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.

How to do it...

  1. First, we define a 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
    }
  2. Next, we define a 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() ...

Get PHP 7 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.