3   About the hydrators

3.1   About hydrators

The hydrator handles the sql query transformation into the objects that were configured in the metadata through the Repository

3.2   Default hydrator

The default hydrator will use the metadata to create the right object and will fill an associative array with, as a key, the table name (or alias used) and the object for as a value

$query = $this->getQuery('SELECT id, name, c.text FROM user LEFT JOIN comment c ON (c.user_id = user.id) WHERE name = :name');
$query->setParams(['name' => 'Sylvain']);
$collection = $query->query();
foreach ($collection as $data) {
  // ...
}

$data contain:

$data =
  [
    'user' => User(3, "Sylvain"),
    'c' => Comment("Bonjour tout le monde")
  ]

3.2.1   SQL join with no data

When the join returns no data, the key ‘c’ will be null

3.2.2   Data without metadata

If you perform a query that returns data that do not match any metadata, whether an aggregation column as SUM(price) or a column that has not been mapped as my_extra_column the hydrator will create a stdClass object with properties corresponding to those columns.

This stdClass object is accessible in the key 0 of the returned array.

$query = $this->getQuery('SELECT name, my_extra_column, SUM(price) as total FROM article');
$collection = $query->query();
foreach ($collection as $data) {
  // ...
}

$data contain:

$data =
  [
    0 => stdClass(
      [total] => 43,
      [my_extra_column] => 'Bic'
    ),
    'article' => Article("Stylo"),
  ]

3.3   The hydrator for a single object

The default hydrator is optimized to return multiple objects when we do a query that is intended to return only one item, it is not the best choice.

You can inject HydratorSingleObject that suit better your needs

$query = $this->getQuery('SELECT id, name, c.text FROM user WHERE name = :name');
$query->setParams(['name' => 'Sylvain']);
$collection = $query->query($this->getCollection(new HydratorSingleObject()));
foreach ($collection as $user) {
  // ...
}

Dans ce cas $user est un objet User.