链式缓存适配器
此适配器允许组合任意数量的其他可用缓存适配器。缓存项从包含它们的第一个适配器中获取,并保存到所有给定的适配器中。这为创建分层缓存提供了一种简单而高效的方法。
ChainAdapter 必须以适配器数组作为参数提供,并可选择性地提供默认缓存生命周期作为其构造函数参数
1 2 3 4 5 6 7 8 9
use Symfony\Component\Cache\Adapter\ChainAdapter;
$cache = new ChainAdapter(
// The ordered list of adapters used to fetch cached items
array $adapters,
// The default lifetime of items propagated from lower adapters to upper ones
$defaultLifetime = 0
);
注意
当在第一个适配器中找不到某个项,但在后续适配器中找到时,此适配器确保将获取的项保存到之前缺少它的所有适配器中。
以下示例展示了如何使用最快和最慢的存储引擎 ApcuAdapter 和 FilesystemAdapter 分别创建链式适配器实例
1 2 3 4 5 6 7 8
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\ChainAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
$cache = new ChainAdapter([
new ApcuAdapter(),
new FilesystemAdapter(),
]);
当调用此适配器的 prune() 方法时,该调用会委托给其所有兼容的缓存适配器。可以安全地混合实现和未实现 PruneableInterface 的适配器,因为不兼容的适配器会被静默忽略
1 2 3 4 5 6 7 8 9 10 11
use Symfony\Component\Cache\Adapter\ApcuAdapter;
use Symfony\Component\Cache\Adapter\ChainAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
$cache = new ChainAdapter([
new ApcuAdapter(), // does NOT implement PruneableInterface
new FilesystemAdapter(), // DOES implement PruneableInterface
]);
// prune will proxy the call to FilesystemAdapter while silently skip ApcuAdapter
$cache->prune();
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。