简体   繁体   English

如何在与学说的共鸣中使用缓存和分页?

[英]How to use caching and pagination in symfony with doctrine?

I have a Symfony REST API application. 我有一个Symfony REST API应用程序。
In repository I retrieve some data and use Doctrine Paginator for pagination, then in controller I serialize that data to JSON with Symfony Serializer. 在存储库中,我检索一些数据并使用Doctrine Paginator进行分页,然后在控制器中,使用Symfony Serializer将数据序列化为JSON。

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. 现在,我想使用Redis实现数据缓存。 How can I do it? 我该怎么做?
Should I inject serializer into repository, serialize my data there and store scalar values in Redis? 我应该将序列化器注入存储库,在其中序列化数据并将标量值存储在Redis中吗?
Or should I use Doctrine Result Cache (which says nothing about paginated queries)? 还是应该使用Doctrine 结果缓存 (关于分页​​查询什么也没有说)?

There are 3 caching mechanism from which you can choose. 您可以选择3种缓存机制。

1) You can use the HttpCache component . 1)您可以使用HttpCache组件 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. 2)您可以从dbal / orm组件中获取ResultCache。 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 ". 3)教义为几个版本引入了一种新的缓存机制,称为“ 第二级缓存 ”。 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 . 序列化器更多是一个view layer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM