Skip to content

Instantly share code, notes, and snippets.

@Tom32i
Last active June 23, 2020 21:04
Show Gist options
  • Save Tom32i/7984541 to your computer and use it in GitHub Desktop.
Save Tom32i/7984541 to your computer and use it in GitHub Desktop.
Simple list hydrator for Symfony2

Simple list hydrator for #Syfmony2

Sample User repository method that return all user names in an array:

/**
 * Find user names
 *
 * @return array
 */
public function findAllNames()
{
    $names = $this->createQueryBuilder('u')
        ->select('DISTINCT(u.name)')
        ->getQuery()
        ->getResult('simple_list_hydrator');

    return $names;
}

Will return:

array("Moony", "Wormtail", "Padfoot", "Prongs");
# Doctrine Configuration
doctrine:
orm:
hydrators:
simple_list_hydrator: "Tom32i\\Hydrator\\SimpleListHydrator"
<?php
namespace Tom32i\Hydrator;
use Doctrine\ORM\Internal\Hydration\AbstractHydrator;
class SimpleListHydrator extends AbstractHydrator
{
/**
* {@inheritdoc}
*/
protected function hydrateAllData()
{
$result = [];
$cache = [];
while ($data = $this->_stmt->fetch(\PDO::FETCH_NUM)) {
$this->hydrateRowData($data, $cache, $result);
}
asort($result);
return $result;
}
/**
* {@inheritdoc}
*/
protected function hydrateRowData(array $data, array &$cache, array &$result)
{
$result[] = $data[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment