PSR-6 和 PSR-16 缓存之间互操作性的适配器
有时,您可能有一个实现了 PSR-16 标准的缓存对象,但需要将其传递给期望 PSR-6 缓存适配器的对象。或者,您可能遇到相反的情况。缓存组件包含两个类,用于 PSR-6 和 PSR-16 缓存之间的双向互操作性。
将 PSR-16 缓存对象用作 PSR-6 缓存
假设您想使用一个需要 PSR-6 缓存池对象的类。例如
1 2 3 4 5 6 7 8 9 10 11 12 13
use Psr\Cache\CacheItemPoolInterface;
// just a made-up class for the example
class GitHubApiClient
{
// ...
// this requires a PSR-6 cache object
public function __construct(CacheItemPoolInterface $cachePool)
{
// ...
}
}
但是,您已经有一个 PSR-16 缓存对象,并且您想将其传递给该类。没问题!缓存组件提供了 Psr16Adapter 类来专门解决这种情况
1 2 3 4 5 6 7 8 9
use Symfony\Component\Cache\Adapter\Psr16Adapter;
// $psr16Cache is the PSR-16 object that you want to use as a PSR-6 one
// a PSR-6 cache that uses your cache internally!
$psr6Cache = new Psr16Adapter($psr16Cache);
// now use this wherever you want
$githubApiClient = new GitHubApiClient($psr6Cache);
将 PSR-6 缓存对象用作 PSR-16 缓存
假设您想使用一个需要 PSR-16 缓存对象的类。例如
1 2 3 4 5 6 7 8 9 10 11 12 13
use Psr\SimpleCache\CacheInterface;
// just a made-up class for the example
class GitHubApiClient
{
// ...
// this requires a PSR-16 cache object
public function __construct(CacheInterface $cache)
{
// ...
}
}
但是,您已经有一个 PSR-6 缓存池对象,并且您想将其传递给该类。没问题!缓存组件提供了 Psr16Cache 类来专门解决这种情况
1 2 3 4 5 6 7 8 9 10 11
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;
// the PSR-6 cache object that you want to use
$psr6Cache = new FilesystemAdapter();
// a PSR-16 cache that uses your cache internally!
$psr16Cache = new Psr16Cache($psr6Cache);
// now use this wherever you want
$githubApiClient = new GitHubApiClient($psr16Cache);
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。