How to serialize an Entity in laminas/mezzio using doctrine and jms/serializer

408 views Asked by At

We're currently working on an API using laminas/mezzio and I'd like to generate different outputs for the details and list routes. I'm looking for a way to generate the following results:

List-Response

{
  "_total_items": 2,
  "_page": 1,
  "_page_count": 1,
  "_links": {
    "self": {
      "href": "https://api.domain.tld/snapshot?page=1"
    }
  },
  "_embedded": {
    "snapshot": [
      {
        "id": "9c81ed3e-4ec4-4c5f-a3a1-d14e499b2607",
        "name": "Lorem Ipsum 1"
      },
      {
        "id": "6381ed3e-4ec4-4c5f-a3a1-d14e499b2633",
        "name": "Lorem Ipsum 2"
      }
    ]
  }
}

Detail-Response

{
  "id": "9c81ed3e-4ec4-4c5f-a3a1-d14e499b2607",
  "name": "Lorem Ipsum 1",
  "foo": "bar",
  "more": "fields"
}

For this purpose, I've found the package jms/serializer. I've added all the annotations required by the serializer and it works. But I'm a bit lost how to integrate this package into laminas/mezzio with doctrine 2 and laminas/mezzio-hal

My ListHandler:

<?php
class ListHandler implements RequestHandlerInterface
{
    protected SnapshotServiceInterface $snapshotService;
    protected HalResponseFactory $halResponseFactory;
    protected ResourceGenerator $resourceGenerator;
    protected int $itemsPerPage;

    public function __construct(
        array $config,
        SnapshotServiceInterface $snapshotService,
        HalResponseFactory $halResponseFactory,
        ResourceGenerator $resourceGenerator
    ) {
        $this->snapshotService = $snapshotService;
        $this->halResponseFactory = $halResponseFactory;
        $this->resourceGenerator = $resourceGenerator;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $paramsQuery = $request->getQueryParams();
        $paramsRoute = $request->getAttributes();
        $params = array_merge($paramsQuery, $paramsRoute);
        $itemsPerPage = (array_key_exists('itemsPerPage', $params)) ? (int)$params['itemsPerPage'] : $this->itemsPerPage;

        $query = $this->snapshotService->getBy($params);
        $paginator = new SnapshotListCollection($query->setMaxResults($itemsPerPage));
        $resource = $this->resourceGenerator->fromObject($paginator, $request);

        return $this->halResponseFactory->createResponse($request, $resource);
    }
} 

I probably need a way to tell doctrine how to hydrate my SnapshotEntity. I've read about a "Lifecycle Event" which should be attached to a Doctrine listener. But all tutorials I'm looking at are written with Symfony in mind. How can I tell doctrine/mezzio/hal to hydrate my entities based on different routes and using the serializer? Can someone point me in the right direction?

Thank you very much!

0

There are 0 answers