如何在Symfony 2中缓存?

Tow*_*wer 42 php caching symfony

我需要使用Symfony 2的缓存系统缓存一些特定于应用程序的数据,以便我可以运行cache:clear清除它.所有缓存都依赖于,app/cache但我如何实际缓存数据呢?

http://symfony.com/doc/current/cookbook/index.html

我看到的唯一主题是关于使用Varnish进行HTML缓存.

Kri*_*ith 78

如果您使用的是Doctrine,则只需使用这些缓存类.

添加服务config.yml:

services:
    cache:
        class: Doctrine\Common\Cache\ApcCache
Run Code Online (Sandbox Code Playgroud)

并在您的控制器中使用它:

if ($fooString = $this->get('cache')->fetch('foo')) {
    $foo = unserialize($fooString);
} else {
    // do the work
    $this->get('cache')->save('foo', serialize($foo));
}
Run Code Online (Sandbox Code Playgroud)

  • 这是Doctrine\Common的一部分.不要将它与ORM,DBAL等混淆."Doctrine Common项目是一个提供核心PHP功能扩展的库." (25认同)
  • 如果我不使用Doctrine怎么办?为什么这是教义的一部分? (20认同)
  • @Tower仍然没有答案吗? (2认同)
  • 有没有办法设定它的时间? (2认同)
  • @FrancisGonzales"save"方法需要第三个`lifetime`参数:http://www.doctrine-project.org/api/common/2.0/class-Doctrine.Common.Cache.Cache.html (2认同)

Мак*_*тов 33

使用Doctrine缓存提供程序的简单方法.首先,注册服务(config.yml中的示例):

services:
    memcached:
        class: Memcached
        calls:
            - [ addServer, ['localhost', 11211] ]
    memcached_cache:
        class: Doctrine\Common\Cache\MemcachedCache
        calls:
            - [ setMemcached, [@memcached] ]
Run Code Online (Sandbox Code Playgroud)

然后使用get服务,例如在controler中:

$cache = $this->get('memcached_cache');
Run Code Online (Sandbox Code Playgroud)

发送另一个服务使用电话:

calls:
    - [ setCacheProvider, [@memcached_cache] ]
Run Code Online (Sandbox Code Playgroud)

或参数:

arguments:
    - @memcached_cache
Run Code Online (Sandbox Code Playgroud)

以同样的方式,您可以使用Doctrine Cache包的其他接口.Doctrine Cache提供了一个非常简单的界面,为其提供了几个开箱即用的实现:

  • ApcCache(需要ext/apc)
  • ArrayCache(在内存中,请求的生命周期)
  • FilesystemCache(不适合高并发)
  • MemcacheCache(需要ext/memcache)
  • MemcachedCache(需要ext/memcached)
  • PhpFileCache(不适合高并发)
  • RedisCache.php(需要ext/phpredis)
  • WinCacheCache.php(需要ext/wincache)
  • XcacheCache.php(需要ext/xcache)
  • ZendDataCache.php(需要Zend Server Platform)

如果您尚未使用Doctrine,则可能需要Common Library for Doctrine项目:php composer.phar require doctrine/common或者只需要Caching库为许多缓存后端提供面向对象的API:php composer.phar require doctrine/cache

如何使用Doctrine Caching,您可以在Doctrine项目网站上的Doctrine Common文档中阅读


Als*_*ian 10

Symfony 3.1提供了一个新的Cache组件.


Ben*_*min 8

Symfony2不提供应用程序层缓存的任何组件.

就像你已经被告知的那样,你可以使用Doctrine Common缓存库http://docs.doctrine-project.org/projects/doctrine-common/en/latest/reference/caching.html

如果您想要更高级的东西,您还可以使用社区提供的缓存包之一.例如,https://github.com/TheBigBrainsCompany/TbbcCacheBundle#cachebundle提供了良好缓存策略的工具.