Hi,
I try to develop a API Rest service with mezzio and have a problem.
I used https://github.com/ezimuel/zend-expressive-api from @enrico that i migrated to Mezzio for my base of structure and testing.
I have a Product model and a Stock model.
When i’m requesting for one product i would like a Stock model embedded. It works!
I got a product with a embed Stock object inside in my json. I proceeded like that:
   // Product model query
    $product = $this->productModel->getProduct($id);
    // Create product HAL from object
    $productHal = $this->resourceGenerator->fromObject($product, $request);
    // Stock model query
    $stock = $this->stockModel->getWithProductId($id);
    // Create stock HAL from object
    $stockHal = $this->resourceGenerator->fromObject($stock, $request);
    // Embed stock to product
    $productHal = $productHal->embed('stocks', [$stockHal]);
    return $this->responseFactory->createResponse($request, $productHal);
But how to do that in a collection?
I have something like that in my Product model but don’t kwow how to add embed Stock in a collection of Product, i know the process have to be done somewhere else…
public function getAll(): Paginator
{
    $select = new Select($this->table->getTable());
    $select->columns($this->fields)
            ->where->equalTo('isActive', 1); 
    $paginatorAdapter = new DbSelect(
        $select,
        $this->table->getAdapter(),
        $this->table->getResultSetPrototype()
    );
    $paginator = new ProductCollection($paginatorAdapter);
    return $paginator;
}
I read somewhere that i have to create a special hydrator for it… Is it right?
  class ProductHydrator extends ObjectPropertyHydrator
   {
    private $stockModel;
    public function __construct(StockModel $stockModel)
    {
        $this->stockModel = $stockModel;
    }
    public function hydrate(array $data, object $object)
    {
        $product = parent::hydrate($data, $object);
        if (null !== $product->id) {
            $stock = $this->stockModel->getWithProductId($product->id);
            $product->stocks = $stock;
        }
        return $product;
    }
 }
It works but i would like to know if it is the right way? Or it exist another way to manage that?
Thanks!