php Symfony 2 缓存 Doctrine 查询结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28498314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:53:46  来源:igfitidea点击:

Symfony 2 cache Doctrine query results

phpsymfonycachingdoctrine-orm

提问by Tomazi

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

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

I have looked at few options such as:

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

  • Symfony annotation cache
  • Doctrine cache
  • Memcache
  • Symfony 注释缓存
  • 教义缓存
  • 内存缓存

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.

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

I.e I have this query:

即我有这个查询:

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');
    }
}

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库use

回答by Tomasz Madeyski

In doctrineto cache queries or results you can do the following:

doctrine缓存查询或结果,你可以做到以下几点:

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
}

Check docfor more info about these methods. This will make yourcache driver working - doesn't matter what driver you are using.

检查 文档以获取有关这些方法的更多信息。这将使your缓存驱动程序工作 - 与您使用的驱动程序无关。

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

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

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

You might also want to check thisand thisblog entries

您可能还想检查这个这个博客条目