0
votes

I have a Symfony REST API application.
In repository I retrieve some data and use Doctrine Paginator for pagination, then in controller I serialize that data to JSON with Symfony Serializer.

Repository method:

public function getCategories($limit, $offset)
    {
        $qb = $this->em->createQueryBuilder()
            ->select('c')
            ->from('Category:Category', 'c')
            ->getQuery()->setFirstResult($offset)
            ->setMaxResults($limit);
        $paginator = new Paginator($qb);
        return ['total' => count($paginator), 'items' => $paginator];
    }

And in controller:

    $data = $this->serializer->serialize($data, 'json', $context);
    return new JsonResponse($data, $code, [], true);

Now I want to implement caching of my data using Redis. How can I do it?
Should I inject serializer into repository, serialize my data there and store scalar values in Redis?
Or should I use Doctrine Result Cache(which says nothing about paginated queries)?

1

1 Answers

1
votes

There are 3 caching mechanism from which you can choose.

1) You can use the HttpCache component. This is a generally a good design if you have large traffic and you know when the data has been changed, so you can invalidate them.

2) You can the ResultCache from the doctrine dbal/orm component. I would use this technique, if this is a heavy query for the database and the result is only valid for a few minutes.

I'm not what do you mean with "which says nothing about paginated queries", because its up to you, which query should be cached and which not.

public function getCategoriesQuery($limit, $offset) 
{
    return $this->createQueryBuilder('c')
        ->getQuery()->setFirstResult($offset)
        ->setMaxResults($limit)->useResultCache(true);
}

3) Doctrine introduced for a few versions a new caching mechanism, which is called "second level cache". This is a more flexible caching mechanism which allows the developers to have more control when the data gets evicted.

The serializer should never been injected to the repository. The repository has only one thing to do, to read data. The serializer is more a view layer.