Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change object type with hydrators, inside a pagination collection with ZendFramework 2 + Doctrine 2

I'm building a RESTful API, and I have problem.

The goal: I want to hydrate a collection, that comes from a Paginator. I mean, inside the collection, I don't want to return a Project object, I want to return a HalCollection of HalResources. To create these HalResources, I need to use the Project object (plus additional information).

The scenario: I create a class ProjectHydrator, that implements HydratorInterface, with the two methods:

class ProjectHydrator implements HydratorInterface  {
public function hydrate(array $data, $project){ .... }
public function extract($project) { .... }
}

I attach this Hydrator to my module, inside the module.config.php

'phlyrestfully' => array (
'renderer' => array (
    'hydrators' => array (
        'MYPROJECT\Entity\Project' => new \MYPROJECT\Hydrators\ProjectHydrator()
        )
    ),
    ......
)

And the fetchAll of the listener method y create the pagination in this way:

$dql = 'SELECT e FROM \MYPROJECT\Entity\Project e';
$query = $this->getEntityManager()->createQuery($dql);  //  Class: \Doctrine\ORM\Query
$ormPaginator       = new \Doctrine\ORM\Tools\Pagination\Paginator($query);                         //Class: Doctrine\ORM\Tools\Pagination\Paginator
$doctrinePaginator  = new \DoctrineORMModule\Paginator\Adapter\DoctrinePaginator($ormPaginator);    //Class: DoctrineORMModule\Paginator\Adapter\DoctrinePaginator
$paginator          = new \Zend\Paginator\Paginator($doctrinePaginator);                            //Class: Zend\Paginator\Paginator
return $paginator;

The problem: The hydrator is being executed... but is called the method "extract", with parameter a Project object. In this method I must return and array, and this is my problem, I want to return a HalResource, not an array.

I want to use the hydrator to change the type of object, from Project object (project Entity object) to a HalResource. To build this HalResource, I want to use the Project object plus an array with other parameters.

What I am doing wrong? Any ideas?

Thank you very much!


1 Answers

No need to extend the Doctrine Paginator, simply set your query hydration mode to hydrate array mode.

use Doctrine\ORM\Query;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as PaginatorAdapter;
use Zend\Paginator\Paginator;

$dql = 'SELECT e FROM \MYPROJECT\Entity\Project e';
$query = $this->getEntityManager()->createQuery($dql);

//Set query hydration mode
$query->setHydrationMode(Query::HYDRATE_ARRAY);

$paginator = new Paginator(new PaginatorAdapter(new DoctrinePaginator($query)));

return $paginator;

Hope it helps.

like image 80
php-dev Avatar answered Oct 29 '25 22:10

php-dev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!