Symfony 2 缓存 Doctrine 查询结果

2022-01-03 00:00:00 caching php symfony doctrine-orm

我正在使用 Doctrine 进行 Symfony2 项目.我想通过向查询添加缓存来优化 API 性能.

I am working on a Symfony2 project using Doctrine. I want to optimise the API performance by adding cache to queries.

我查看了几个选项,例如:

I have looked at few options such as:

  • Symfony 注释缓存
  • 教义缓存
  • 内存缓存

不确定我应该使用哪个,但对我来说似乎在 Doctrine 级别缓存数据是最合适的.

Not to sure with which one I should go but to me it seems like caching data at Doctrine level would be most suitable.

说我希望有人帮助我或指导我如何设置 Doctrine 缓存并解释它究竟是如何工作的.

Saying that I would like someone to help me or guide me how to set up Doctrine cache and explain how it exactly works.

即我有这个查询:

class QueryFactory

    protected $connect;

    public function __construct(Connection $connection)
    {
        $this->connect = $connection;
    }

    private function myQuery()
    {
        return $this->connect->createQueryBuilder()
            ->select('user_id')
            ->from('users', 'u')
            ->where('u.user_id = 2');
    }
}

我将如何向该查询添加缓存?有没有我需要注入任何我需要使用的东西的Doctrine库?

How would I add a cache to this query? Is there any Doctrine library I need to inject any thing I need to use?

推荐答案

doctrine 中缓存查询或结果,您可以执行以下操作:

In doctrine to cache queries or results you can do the following:

private function myQuery()
{
    return $this->connect->createQueryBuilder()
        ->select('user_id')
        ->from('users', 'u')
        ->where('u.user_id = 2')
        ->getQuery()
        ->useQueryCache(true)    // here
        ->useResultCache(true);  // and here
}

检查 doc 有关这些方法的更多信息.这将使 您的 缓存驱动程序正常工作 - 与您使用的驱动程序无关.

Check doc for more info about these methods. This will make your cache driver working - doesn't matter what driver you are using.

要配置 Symfony 以使用特定的查询驱动程序,您需要在 config.yml 中调整您的设置 - 检查 this 查看完整的选项列表.缓存中重要的是(这是 apc 配置示例):

To configure Symfony to use specific query driver you need to adjust your settings in config.yml - check this to see complete list of options. What is important in your cache is (this is apc configuration example):

entity_managers:
        some_em:
            query_cache_driver: apc
            metadata_cache_driver: apc
            result_cache_driver: apc

您可能还想查看 this 和 这个 博客条目

You might also want to check this and this blog entries

相关文章