在Symfony 3.1中,我们添加了一个 全新的Cache组件,它实现的是 PSR-6: Caching Interface 标准。在Symfony 3.2中,我们改进了此组件,连同 tagged caches 和 其他改进点。
虽然Cache组件提供了企业级程序所需的每一样东西,对于小型程序,它在使用时略显笨重。例如,要使用一个基于file system(文件系统)的缓存来存、取以及删除一个简单的变量,你必须做出以下处理:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | use Symfony\Component\Cache\Adapter\FilesystemAdapter;
$cache = new FilesystemAdapter();
// save an item in the cache / 把一个item(元素)存入缓存
$numProducts = $cache->getItem('stats.num_products');
$numProducts->set(4711);
$cache->save($numProducts);
// fetch the item from the cache / 从缓存中取出元素
$numProducts = $cache->getItem('stats.num_products');
if (!$numProducts->isHit()) {
// ... item does not exist in the cache
} else {
$total = $numProducts->get();
}
// remove the item from the cache / 从缓存中删除元素
$cache->deleteItem('stats.num_products'); |
在Symfony 3.3中,我们决定改进Cache组件,遵循了一个相关的、被称为 PSR-16: Common Interface for Caching Libraries 的标准(PSR-16:缓存类库的普通接口)。简单说来,这是个简化版的缓存架构,可以从缓存中存取和删除元素。使用新缓存时,前例会像下面这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | use Symfony\Component\Cache\Simple\FilesystemCache;
$cache = new FilesystemCache();
// save an item in the cache / 把一个item(元素)存入缓存
$cache->set('stats.num_products', 4711);
// fetch the item from the cache / 从缓存中删除元素
if (!$cache->has('stats.num_products')) {
// ... item does not exist in the cache / 元素在缓存中不存在时
} else {
$total = $cache->get('stats.num_products');
}
// remove the item from the cache / 从缓存中删除元素
$cache->delete('stats.num_products'); |
缓存不存在时,simple cache允许你定义默认值。它定义了 setMultiple()
, getMultiple()
以及 deleteMultiple()
方法,可以和若干元素(items)同时工作。
不管是常规缓存还是简单缓存,统统支持相同的缓存适配器(cache adapters,如file system, Redis, Memcache等等),并且两个提供的是相似的性能,因此决定使用哪个,依你的缓存所需之功能而定。