How can the Hydrator Pattern be used to create entities with only specific properties in PHP?

When creating entities in PHP, we may want to hydrate them with only specific properties from a given data source. The Hydrator Pattern can be used to achieve this by defining a hydrator class that takes an entity object and a data array as input, and populates the entity with only the specified properties. This allows for more control over which properties are set on the entity.

class Hydrator {
    public function hydrate(Entity $entity, array $data) {
        foreach ($data as $key => $value) {
            if (property_exists($entity, $key)) {
                $entity->$key = $value;
            }
        }
    }
}

class Entity {
    public $id;
    public $name;
}

// Example usage
$hydrator = new Hydrator();
$data = ['id' => 1, 'name' => 'John', 'age' => 30];
$entity = new Entity();
$hydrator->hydrate($entity, $data);

var_dump($entity);